182k views
4 votes
The magic square is an arrangement of numbers in a square grid in such a way that the sum of the numbers in each row, and in each column, and in each diagonal is the same. MATLAB has a built-in function _magic(n) that returns an n times n magic square. In a script file create a (5 times 5) magic square, and then test the properties of the resulting matrix by finding the sum of the elements in each row, in each column and in both diagonals. In each case, use MATLAB's built-in function _sum. (Other functions that can be useful are diag and fliplr.)

1 Answer

4 votes

Answer:

See the explanation for the answer;

Step-by-step explanation:

Matlab code is as given below

-------------------------------------------------------------------------------------Start of code

% Program to create a magic square and verify it

clc

M= magic(5)

% To find sum of elements of each row

r1= sum(M(1,:)) % Sum of row 1

r2= sum(M(2,:)) % Sum of row 2

r3= sum(M(3,:)) % Sum of row 3

r4= sum(M(4,:)) % Sum of row 4

r5= sum(M(5,:)) % Sum of row 5

% To find sum of each coloumn

c1= sum(M(:,1)) % Sum of coloumn 1

c2= sum(M(:,2)) % Sum of coloumn 2

c2= sum(M(:,3)) % Sum of coloumn 3

c2= sum(M(:,4)) % Sum of coloumn 4

c2= sum(M(:,5)) % Sum of coloumn 5

% To find sum of diagonal

d1= sum(diag(M)) % Sum of principal diagonal elements

d2= sum(diag(fliplr(M)))

-------------------------------------------------------------------------------End of code

Following results are obtained when executed.

M =

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9

r1 =

65

r2 =

65

r3 =

65

r4 =

65

r5 =

65

c1 =

65

c2 =

65

c2 =

65

c2 =

65

c2 =

65

d1 =

65

d2 =

65

User Michael Beeson
by
3.4k points