Number to matrix
조회 수: 29 (최근 30일)
이전 댓글 표시
Hello!
I am very new to MatLab. I am wondering, what is the simplest way to convert a 5-digit number into a matrix of those 5 digits.
Thanks,
댓글 수: 3
답변 (2개)
Walter Roberson
2012년 2월 9일
sprintf('%d', TheNumber) - '0'
is the simplest, but not the most efficient.
댓글 수: 0
Benjamin Schwabe
2012년 2월 9일
You can do that by simply using the following code:
p = 12345; % define your number
pstr=num2str(p);
n=length(pstr);
v=zeros(n,1);
for k=1:n
v(k)=str2double(pstr(k));
end
It will work for all integer numbers. For non Integer numbers, the "." will be transformed into 'NaN'.
댓글 수: 2
Benjamin Schwabe
2012년 2월 9일
Maybe some more details:
I convert the number to a string with num2str, then I take each character of the string and transfort it back to a number.
If you want to have a row vector instead of a column, just replace
v=zeros(n,1); by v=zeros(1,n);
Walter Roberson
2012년 2월 10일
When you are dealing with single digits, subtracting the character '0' is much more efficient than str2double().
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!