Determine the magic sum from a magic square

조회 수: 18 (최근 30일)
Farooq
Farooq 2022년 9월 22일
댓글: Nathan Hardenberg 2023년 7월 25일
Determine for a magic square of order n, the magic sum m. For example m=15 for a magic square of order 3.
For this problem I wrote:
m = sum(n)
This gave me 15 15 15. Why is this not correct?
I then tried
m = sum(n(1, :))
This gave me 15. Why is this not correct?
I don't understand why my answer is not accepted. This is for Cody Problem 1087: Magic is simple (for beginners).
  댓글 수: 1
David Goodmanson
David Goodmanson 2022년 9월 22일
Hi Farook,
It looks like you are given the size of the magic square, but not the magic square itself. So if all you are given is that the magic square is 3x3, how do you obtain 15 from n=3?

댓글을 달려면 로그인하십시오.

채택된 답변

Davide Masiello
Davide Masiello 2022년 9월 22일
편집: Davide Masiello 2022년 9월 22일
I think you are inputting the magic square itself to your function, rather than its order.
I believe the relation between a magic square order (n) and the magic sum (S) is
So your function should be
function out = magic_sum(n)
out = n*(n^2+1)/2
end
  댓글 수: 2
Farooq
Farooq 2022년 9월 22일
Thank you for your help!
Nathan Hardenberg
Nathan Hardenberg 2023년 7월 25일
While the formula is a valid solution I think the intended way is to sum up one colum or row, since all rows/colums and diagonals do sum up to the same number:
mag_sqr = magic(3)
mag_sqr = 3×3
8 1 6 3 5 7 4 9 2
sol1 = sum(mag_sqr(:,1)) % sum up first colum
sol1 = 15
sol2 = sum(mag_sqr(1,:)) % sum up first row
sol2 = 15

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by