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.
Show older comments
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?
2 Comments
Jorge Briceño
on 4 Feb 2018
Hi everyone,
I came up with a different solution.
function [ sumS ] = spiral_diag_sum( n )
% If statement for n = 1.
sumS = 1;
if n == 1
return
% If statement for n > 1
elseif n>1
% Value when n = 1.
for counter = n:-2:2
% This code sums the corner values of each layer from a 3 x 3 to a n x n
% matrix. The counter is evaluating the layers values.
sumS = sumS + sum (counter^2:-(counter-1):(counter-2)^2+1);
end
end
end
Champions2015, maybe you should try understanding the problem first. Use simple code such as:
(counter^2:-(counter-1):(counter-2)^2+1)
With a counter = 3 and 5, pay attention to the values. Your code is using a formula a bit complex to understand.
I hope it helps.
William Gallego
on 4 Nov 2018
I always like your solutions and explanations. Thanks again!
function s = spiral_diag_sum(n)
if n==1
s=1;
else
a=spiral(n);
b=sum(diag(a));
a(1:end,:)=a(end:-1:1,:);
c=sum(diag(a));
d=a((1+n)/2,(1+n)/2);
s=b+c-d;
end
Accepted Answer
More Answers (3)
Erfan Pakdamanian
on 23 May 2018
Edited: Erfan Pakdamanian
on 23 May 2018
1 vote
function s= spiral_diag_sum(n)
sp=spiral(n);
s=sum(diag(sp))+sum(diag(fliplr(sp)))-1;
Vignesh M
on 8 May 2018
%if you dont want recursion & want to use loops instead, make use of below code
function sum = spiral_diag_sum(n)
if n == 1
sum = 1;
else
sum_it = 0;
m = 1:2:n;
for m = m(m~=1)
sum_it = 4*(m^2) - 6*(m-1) + sum_it ;
end
sum = sum_it + 1 ; % added 1(center element)
end
end
Govind Sankar Madhavan Pillai Ramachandran Nair
on 7 Oct 2018
0 votes
Hi, I am trying to attempt the same question. But my problem is where is the spiral MATRIX.How do we compute the sum without the MATRIX.
function spiralsum = spiral_diag_sum(n) spiralsum = 0; for i = 1:n for j = 1:n if(i==j) spiralsum = spiralsum + M(i,j); end end end spiralsum = spiralsum + sum(M(n*n:-(n-1):1)) - M(1,1) - M(n,n)-M((floor(n/2))+1,(floor(n/2))+1) end
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!