How can I create a nested loop ?

조회 수: 549(최근 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
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

범주

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by