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 visualizzazione (ultimi 30 giorni)
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

Risposte (1)

RAMAKANT SHAKYA
RAMAKANT SHAKYA il 7 Feb 2019
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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by