views:

38

answers:

3

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 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
A: 

Why don't you just use sum()?

Oli Charlesworth
not allowed to for this problem
Alberto
@Alberto: Ok! Then please edit your question and add that fact. Also, please tag your question as "homework".
Oli Charlesworth
sorry... fixed it
Alberto
+2  A: 

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:

  1. 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.
  2. Cumulate the values. If you assign to sum at each iteration, you'll throw away the result of other iterations.
  3. There is no point in writing the outer loop if you're going to hardcode j+1, j+2, etc. in the inner loop.
  4. Fix the inner loop so that it starts iterating at 1.
  5. Suppress output in the inner loop by using a semicolon to get a clean result.
André Caron
Ah, I see you've simply fixed the code :) Well, Alberto can ignore my answer then.
dark_charlie
Sorry about that! I find it more readable with the comments outside the code block, though :-)
André Caron
it worked thanks a lot!
Alberto
Also, one shouldn't use variable names that are equivalent to function names, such as `sum`
Jonas
+1  A: 

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
dark_charlie

related questions