MATLAB: How to use a for loop to sum a random 12×12 matrix.

for looploopMATLABmatrixrandomsum

This is an assignment so I know there are other ways to sum but the teacher asks specifically for a for loop. I'm not familiar with the for loop so please bear with me.
A = randi([10,10],[12,12])
total=0
for i=1:size(A,1)
for j=1:size(A,2)
total=total + A(i,j)
end
end
total = sum(A(:))
Thanks in advance.

Best Answer

EDITED
A = randi([10,10],[12,12]);
total=0;
for i=1:size(A,1)
for j=1:size(A,2)
total=total + A(i,j);
end
end
total
sum(A(:))
total == sum(A(:)) % to check whether if your result is correct or not if it returns one then your answer is correct
bsxfun(@eq,total,sum(A(:))) % if your using prior version of matlab to check if they are equal
command window:
>> total
total =
1440
>> sum(A(:))
ans =
1440
>>
Related Question