Using num2str inside the for loop

3 次查看(过去 30 天)
Chiranjibi
Chiranjibi 2014-11-12
回答: Star Strider 2014-11-12
I'm trying to using num2str inside the for loop;
firstDay = 1;
lastDay = 5;
>> for i= firstDay:lastDay
f = num2str(i);
end
I was expecting f = 1 2 3 4 5, but I got f = 5 only. When I use f(i), this gives error though. Any help would be appreciated.

回答(2 个)

pietro
pietro 2014-11-12
You got only 5 because you haven't used f as an array. Here the right code:
firstDay = 1;
lastDay = 5;
for i= firstDay:lastDay
f(i) = num2str(i);
end

Star Strider
Star Strider 2014-11-12
I don’t get an error subscripting it in R2014b, but there may be version differences.
A cell array should work:
firstDay = 1;
lastDay = 5;
for i= firstDay:lastDay
f{i} = num2str(i);
end
Note the curly braces ‘{}’ around the subscript, indicating a cell array.

类别

Help CenterFile Exchange 中查找有关 Linear Algebra 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by