How to use nested for loops?
显示 更早的评论
I am very new to MATLAB, and I have been trying to figure out how to use nested for loops correctly. I want to print out :
1
121
12321
1234321
123454321
what should I do if there are a varying number of columns? Any help would be greatly appreciated.
3 个评论
Walter Roberson
2018-4-10
What have you tried so far?
Yasmin Touly
2018-4-10
Walter Roberson
2018-4-10
for variable = something : something_else
for another_variable = thing2 : thing3
% do something involving variable and another_variable
end
end
回答(1 个)
No need for nested for loops. Try this:
i=1;n=5;
while i<=n
fprintf('%d',[1:i-1 i:-1:1]);
fprintf('\n');
i=i+1;
end
6 个评论
Walter Roberson
2018-4-10
... This was a homework question. It has come up before as a homework question.
Birdman
2018-4-10
There is nothing mentioned in the question that it is a homework.
Yasmin Touly
2018-4-10
Birdman
2018-4-10
Of course you can, but isn't this one simpler?
Yasmin Touly
2018-4-10
Birdman
2018-4-10
n=5;
for j=1:n
for i=1:j
end
fprintf('%d',[1:i-1 i:-1:1]);
fprintf('\n');
end
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!