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. For example, starting with the number 1 and moving to the right in a c

1 次查看(过去 30 天)
Hi, I am trying to attempt this 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

回答(1 个)

RAMAKANT SHAKYA
RAMAKANT SHAKYA 2019-2-7
function sd=spiral_diag_sum(n)
s1=0;
s2=0;
a=spiral(n);
for r=1:n %for below the diagonal elements
s1=s1+sum(a(r,r));
end
a=flip(a); %flip the matrix daigonally
for s=1:n % elements above the daigonal but the come to below after flip
s2=s2+sum(a(s,s));
end
sd=s1 + s2-a((n+1)/2,(n+1)/2); % element which come two times i.e. cen
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by