views:

2774

answers:

2

Given the matrix:

A=[1 2 3; 4 5 6; 7 8 9]
  1. how would you use the for loop to compute the sum of the elements in matrix?
  2. write a one line MATLAB command using the function sum() to sum the matrix elements in A

My answer:

1)

for j=1:3,
    for i=j:3,
        A(i,:) = A(i,:)+A(j+1,:)+A(j+2,:)
    end
end

2)

sum(A)

Is that the correct answer? I didn't know how to use if, while and for... Can anyone explain it to me?

+7  A: 

1)

total = 0;
for i=1:size(A,1)
  for j=1:size(A,2)
    total = total + A(i,j);
  end
end

2)

total = sum(A(:));
merv
Love the avatar by the way. That baby looks like he's about to start a fight! =)
gnovice
And if you use 1) instead of 2) when you are actually using MATLAB for something real, then you need to die a slow horrible death ;)
kigurai
I know.. How cute is that baby!
merv
+4  A: 

Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:

total = 0;
for i = 1:numel(A)
  total = total+A(i);
end
gnovice

related questions