Reputation: 43
I need to be able to check to see if the sums of rows, columns, and diagonals are all equal to one another in a matrix. I've tried everything I could think of and nothing has come close. Any help would be appreciated!
Upvotes: 0
Views: 81
Reputation: 422
When you use sum for matrix, it will give sum of columns. This operation can be repeated for transpose of 'a'. If I don't misunderstand your question, diagonals can be found diag function and 'a(sqrt(end):sqrt(end)-1:end-1)'. The code is given below:
a = [1 2 3; 4 5 6; 7 8 9]; %%Let 'a' given matrix
if(sum(diag(a)) == sum(a(sqrt(end):sqrt(end)-1:end-1)))%% anti diagonal vs diagonal
disp('Diagonals are equal')
end
rows = sum(a');
if(all(rows==rows(1))) %% rows
disp('Rows are equal')
end
columns = sum(a);
if(all(columns==columns(1))) %% columns
disp('Columns are equal')
end
Upvotes: 1