Sum of rows in Magic square using nested for-loops

Hello there,
In my task, we're supposed to create a Magic matrix of 10 and find out the sum of each individual rows before creating a 10x1 vector output displaying the results of each rows. I understand that this can be done simply by using
for i = 1:1:numel(10);
sumRow = sum(matrix, 2);
end
but we are required to do it with nested for-loops instead. Can somebody kindly help me with this? Thank you!

2 Comments

Actually, the whole lot can be done without a single loop and would be the efficient way to do it in matlab.
If you are asked to use double for loop, I would thing you have to convert that sum into a loop.
A pointless exercise, in my opinion. There are plenty of ways to teach loops in matlab that don't involve teaching bad habits as well.
Note that as written your loop is pointless. numel(10) is 1.
"I understand that this can be done simply..."
without a loop:
sum(matrix,2)

Sign in to comment.

Answers (1)

without loop is better:
matrix=magic(10);
sumRow=sum(matrix,2)
with loop (inefficient) according to your requirement:
matrix=magic(10);
n=size(matrix,1);
sumRow = cell(1,n)
for i = 1:n
sumRow{i} = sum(matrix(i,:), 2);
end
sumRow = cell2mat(sumRow{:})

3 Comments

"...we are required to do it with nested for-loops..."
and furthermore "we" means OP, not one of us
Yes, we do get very unnecessary and inefficient questions at times, unfortunately - but I reckon the intention is to get us to understand the concept and hence apply it better.
Thanks all for the help nonetheless =)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2016a

Tags

Asked:

on 17 Nov 2018

Commented:

on 17 Nov 2018

Community Treasure Hunt

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

Start Hunting!