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.
이전 댓글 표시
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
Jorge Briceño
2018년 2월 4일
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
2018년 11월 4일
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
채택된 답변
추가 답변 (3개)
Erfan Pakdamanian
2018년 5월 23일
편집: Erfan Pakdamanian
2018년 5월 23일
1 개 추천
function s= spiral_diag_sum(n)
sp=spiral(n);
s=sum(diag(sp))+sum(diag(fliplr(sp)))-1;
Vignesh M
2018년 5월 8일
%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
2018년 10월 7일
0 개 추천
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
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!