Using num2str with negative numbers
조회 수: 8 (최근 30일)
이전 댓글 표시
Hi, i'm working with num2str but I can't get a coherent matlab answer.
if the numeros matrix doesn't have a negative number it works like the following
clear all
clc
numeros=[1.5 3.4 5.3 7.2;
2.5 4.6 6.5 8.7];
parametro_numero_datos = ['N' num2str(length(numeros),'%d')]
j=0;
for i = 0 : 2 : length(numeros)+2
requestID(i+1,:) = ['i' num2str(numeros(1,j+1),'%-5.2f')];
requestID(i+2,:) = ['d' num2str(numeros(2,j+1),'%-5.2f')];
j=j+1;
end
requestID
the answer is:
parametro_numero_datos =
'N4'
requestID =
8×5 char array
'i1.50'
'd2.50'
'i3.40'
'd4.60'
'i5.30'
'd6.50'
'i7.20'
'd8.70'
but if i have a negative number in the numeros matrix, it doesn't work
clear all
clc
numeros=[1.5 -3.4 5.3 7.2;
2.5 4.6 6.5 8.7];
parametro_numero_datos = ['N' num2str(length(numeros),'%d')]
% requestID = ['i' num2str(numeros(1,1),'%.4f')]
% requestID = ['d' num2str(numeros(2,1),'%.4f')]
j=0;
for i = 0 : 2 : length(numeros)+2
requestID(i+1,:) = ['i' num2str(numeros(1,j+1),'%-5.2f')];
requestID(i+2,:) = ['d' num2str(numeros(2,j+1),'%-5.2f')];
j=j+1;
end
requestID
and the answer is:
parametro_numero_datos =
'N4'
Unable to perform assignment because the size of the left
side is 1-by-5 and the size of the right side is 1-by-6.
Error in Concatenacion_string_numero (line 15)
requestID(i+1,:) = ['i'
num2str(numeros(1,j+1),'%-5.2f')];
>>
colud you please help me?
댓글 수: 0
답변 (2개)
Star Strider
2019년 2월 28일
It is best to go with cell arrays here:
j=0;
for i = 0 : 2 : length(numeros)+2
requestID{i+1} = ['i' num2str(numeros(1,j+1),'%-5.2f')];
requestID{i+2} = ['d' num2str(numeros(2,j+1),'%-5.2f')];
j=j+1;
end
although using the sprintfc (undocumented) or the compose (link) function would be your best option, avoiding the loop entirely:
i = 0 : 2 : length(numeros)+2;
requestID(i+1) = sprintfc('i%-5.2f', numeros(1,:));
requestID(i+2) = sprintfc('d%-5.2f', numeros(2,:));
similarly:
i = 0 : 2 : length(numeros)+2;
requestID(i+1) = compose('i%-5.2f', numeros(1,:));
requestID(i+2) = compose('d%-5.2f', numeros(2,:));
Experiment to get the result you want.
댓글 수: 0
Juan Jose Ortiz Torres
2019년 3월 13일
댓글 수: 2
Star Strider
2019년 3월 13일
Don’t use a loop. Just do this:
numeros=[1.5 -3.4 5.3 7.2;
2.5 4.6 6.5 8.7];
i = 0 : 2 : length(numeros)+2;
requestID(i+1) = sprintfc('i%-5.2f', numeros(1,:));
requestID(i+2) = sprintfc('d%-5.2f', numeros(2,:));
Then:
Result = requestID
produces:
Result =
1×8 cell array
Columns 1 through 7
{'i1.50 '} {'d2.50 '} {'i-3.40'} {'d4.60 '} {'i5.30 '} {'d6.50 '} {'i7.20 '}
Column 8
{'d8.70 '}
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!