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 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Govind Sankar Madhavan Pillai Ramachandran Nair
el 7 de Oct. de 2018
Editada: James Tursa
el 7 de Feb. de 2019
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
0 comentarios
Respuestas (1)
RAMAKANT SHAKYA
el 7 de Feb. de 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
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!