Summation after looping

조회 수: 4 (최근 30일)
Fajar Muharrom
Fajar Muharrom 2012년 5월 16일
I got a problem with summation after looping. Here is the problem :
------------------------------------------
for ri = 0:3
if ri == 0
mi = 1
elseif i > 0
mi = 1
end
end
r = sum(ri)
------------------------------------------
I'm expecting the result from r was 6 (0+1+2+3) but its result was 3. I think the sum command only read the last ri which is 3 and neglecting the other ri.
Any answer will be appreciated. Thanks!

채택된 답변

Matt Kindig
Matt Kindig 2012년 5월 16일
When you use the 'for' statement, you iteratively set ri to each of the values 0, 1, 2, 3. Thus ri only contains 3 after the loop. Instead, assign ri=0:3 to a different variable and have the for loop iterate over that.
For example,
rr = 0:3;
for ri=rr,
if ri == 0
mi = 1
elseif i > 0
mi = 1
end
end
r = sum(rr); %this will be 6
  댓글 수: 1
Fajar Muharrom
Fajar Muharrom 2012년 5월 16일
Thank you Matt Kindig :))

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Fajar Muharrom
Fajar Muharrom 2012년 5월 16일
1st problem was solved. but i got another one, it's similar with the 1st one. I couldn't get the right sum.
-----------------------------------------
i = 0:3;
rx = i
ry = i
rz = i
for r = i
ri = [r r r]
if r == 0
mi = 1
elseif r > 0
mi = 1
end
ri_mi = ri*mi
end
m = 3*mi
rC= 1/m*[sum(ri_mi,1)]
-----------------------------------------
in this case the sum of ri_mi only take the last mi_ri from the looping command. Do you have any idea to solve this problem, Matt Kindig? I will very appreciate it.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by