Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function called spiral_diag_sum that takes an odd positive integer n as

ID: 3836331 • Letter: W

Question

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 clockwise direction, a 5-by-5 spiral is formed as follows:

21

22

23

24

25

20

7

8

9

10

19

6

1

2

11

18

5

4

3

12

17

16

15

14

13

The sum of the red elements above is 101. Hint: the problem does not ask for the matrix itself.

21

22

23

24

25

20

7

8

9

10

19

6

1

2

11

18

5

4

3

12

17

16

15

14

13

Explanation / Answer

function [reqSum] = spiral_diag_sum(n)
reqSum = 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
temp=4*(i + mult*8) + 6*(i-1);
reqSum = reqSum+temp;
end
end

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote