How can I create a nested loop ?

547 ビュー (過去 30 日間)
Samantha Cepeda
Samantha Cepeda 2018 年 4 月 9 日
コメント済み: Wiqas Ahmad 2021 年 3 月 18 日
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 件のコメント
Samantha Cepeda
Samantha Cepeda 2018 年 4 月 9 日
編集済み: Samantha Cepeda 2018 年 4 月 9 日
clear, clc
for i = 1:5
for j = 1:8
b(i,j) = i + j;
end
end
fprintf ( '%g \t', sum)
yes, it is a homework. I took C++ like two years ago and I'm using Matlab now. I'm a little bit lost and worried. Thank you for your help. I didn't quite understand when you referred to 'You should initialize an array (e.g. with the zeros function) before the loop.' What's the zeros function? I've seen people using j=0 or i=0 at the beginning, is that a case when I need to initialize a variable or not at all?
Wiqas Ahmad
Wiqas Ahmad 2021 年 3 月 18 日
How to write b if there are three loops indices, i.e i,j,k?

サインインしてコメントする。

採用された回答

Von Duesenberg
Von Duesenberg 2018 年 4 月 9 日
Here is a possible solution ; adapt it if it doesn't quite do what you had in mind :
iMax = 5;
jMax = 8;
myArray = zeros(iMax, jMax);
for iIdx = 1:iMax
for jIdx = 1:jMax
myArray(iIdx,jIdx) = iIdx + jIdx;
end
end
  1 件のコメント
Samantha Cepeda
Samantha Cepeda 2018 年 4 月 10 日
Thank you so much!

サインインしてコメントする。

その他の回答 (1 件)

muhammad mazhar
muhammad mazhar 2019 年 10 月 7 日
if we have double sigma used for nested loop with energy formula how coulid we implment in matalab like we have an equationUntitled.png

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by