I want to print a different statement for each iteration of a for-loop. I have tried assigning each statement to a variable, putting each variable in a vector and calling a different index of the vector for each iteration like this:
A = 1st statement
B = 2nd statement
C = 3rd statement
v = [A,B,C]
for i = 1:3
fprintf('%s',v(i))
end
but it only prints the first statement one letter per iteration. What would be a better way to do this?
In a 1xn
array, n
alphabets will be stored. That is why you see first three letters getting printed ( i=1:3
). Assuming all the statements do not have the same length, you could save A,B,C
in a cell array. Then access it as usual.
v={A;B;C};
for i = 1:size(v,1) %always try to use size(v,1) instead of hard-coding.
fprintf('%s',v{i,1})
end
If all statements have the same length, then you have them in a matrix.
v=[A;B;C];
for i = 1:size(v,1) %always try to use size(v,1) instead of hard-coding.
fprintf('%s',v(i,:))
end
You can use the following ...
A = '1st statement'
B = '2nd statement'
C = '3rd statement'
v = {A;B;C}
for i = 1:3
fprintf('%s ',v{i,1}))
end
Note the use of {;;;}
(cell array ... http://uk.mathworks.com/help/matlab/cell-arrays.html )
rather than [,,,]
(matrix... http://uk.mathworks.com/help/matlab/learn_matlab/matrices-and-arrays.html ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.