MATLAB: Write a function called spiral_diag_sum that takes an odd positive integer n as an input and computes the sum of all the elements in the two diagonals of the n-by-n spiral matrix.

spiral_diag_sum

function [ MySum ] = spiral_diag_sum( n )
MySum=1;
if n==1
return
end
for i=3:2:n
mult=0;
j=0;
while j <= (i-3)/2
mult=mult+j;
j=j+1;
end
MySum=MySum+(4*(i+mult*8)+6*(i-1));
end
end
this for some reason works but i dont undestand how. What does the while loop do? And how do you figure out the MySum part?

Best Answer

There are many ways to solve this coding problem. The most common way is to divide the spiral matrix into layers, find a pattern and accumulate the sum of 4 corners of each layer.
You may refer to the following link, but keep in mind that this code uses a different pattern for sum of each layer's corner. Hint: start from bottom right instead of top right http://www.geeksforgeeks.org/sum-diagonals-spiral-odd-order-square-matrix/
Related Question