MATLAB Matrix Sum using Nested For
I am trying to find the sum of the following matrix in matlab [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1]
I am trying to do so using a nested for statement yet i keep getting errors. please help
Must use nested for
My code:
A = [1 1 1 1; 1 2开发者_StackOverflow社区 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
for j=1:4,
for i=1:6,
sum = A(j,:)+A(j+1,:)+A(j+2,:)
end
end
You will need to change your code from this:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
for j=1:4,
for i=j:6,
sum = A(j,:)+A(j+1,:)+A(j+2,:);
end
end
to this:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
sum = 0;
for j=1:4,
for i=1:6,
sum = sum + A(j,i);
end
end
Note various modifications:
- Initialize
sum=0
. If you're using this in the interpreter, you'll be starting off with the previous result, guranteeing you don't get the right result. - Cumulate the values. If you assign to sum at each iteration, you'll throw away the result of other iterations.
- There is no point in writing the outer loop if you're going to hardcode
j+1
,j+2
, etc. in the inner loop. - Fix the inner loop so that it starts iterating at 1.
- Suppress output in the inner loop by using a semicolon to get a clean result.
I will not post the corrected code, I'll instead add comments to the code you posted:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
% you are missing sum initialization here - you should first set sum to zero
for j=1:4, % there is no comma needed at the end
for i=j:6, % you want to iterate all the rows, from 1 to 6
sum = A(j,:)+A(j+1,:)+A(j+2,:) % you should be adding to the sum - i.e sum is sum + current field A(j, i)
end
end
Why don't you just use sum()
?
精彩评论