How can I create a nested loop ?
显示 更早的评论
Please, I'm trying to solve this problem: Create two “for loops”, one for i running from 1 to 5 by 1 and the other nested inside the first for j running from 1 to 8 by 1. Inside the nested loop, calculate the sum of the current I and j values and output the sum to the user followed by a tab.
I tried and did this:
clear, clc
i=0; j=0;
for i = 1:1:5 for j = 1:1:8
sum(i,j) = i + j;
end
end
fprintf ( '%g \t', sum)
I want to see if I did it right, I'm still confused on "sum" value. Thank you
3 个评论
Von Duesenberg
2018-4-9
Quick comment (I suppose this is homework): you don't need to initialize your i and j (BTW it's better to avoid such variable names) before the loop. And the step size of 1 is the default in a for loop so you don't have to state it explicitly. It seems that you want to store the result in a variable called "sum"... Matlab has a built-in function with the same name, so you'd better avoid this. You should initialize an array (e.g. with the zeros function) before the loop. Hope this helps.
Samantha Cepeda
2018-4-9
编辑:Samantha Cepeda
2018-4-9
Wiqas Ahmad
2021-3-18
How to write b if there are three loops indices, i.e i,j,k?
采纳的回答
更多回答(1 个)
muhammad mazhar
2019-10-7
0 个投票
if we have double sigma used for nested loop with energy formula how coulid we implment in matalab like we have an equation

类别
在 帮助中心 和 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!