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

조회 수: 2 (최근 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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by