I Need Help write code in MATLAB, please don\'t write in C, or Java, or C++. I r
ID: 3661610 • Letter: I
Question
I Need Help write code in MATLAB, please don't write in C, or Java, or C++. I really appreciate if you can write this in MATLAB. Thank you
Lab Exercise: A magic square is a square of numbers in which the sum of each column, the sum of each row, and the sum of each diagonal is the same. A description is found at http://en.wikipedia.org/wiki/Magic square. A magic square is best obtained using the Siamese method, http://en.wikipedia.org/wiki/Siamese_method Write a function that uses this method, iterating through a matrix, to create a magic square of size n where n is an odd number equal or greater to 3. Hint: start by making an array of size n using the zeros() command. Use an iterator i starting at i-1, and two position variables x and y, as part of a loop: while i is less than n2. Start at the top row, middle column (get that by: x position is (n-1)/2+1, y position is 1). Place a 1 there. Move upward and to the right (subtract 1 from y and add 1 to x, wrapping around if the edge of the square is reached). If there is a number there (i.e. if the number in that position is nonzero), move back, and move one square down instead. If there is a number there, move down (wrapping around the edge of the square) until an empty space is reachedExplanation / Answer
The following code creates a magic square when n is greated or equal to 3 or odd in matlab:
proc iml
/* definition of the function to find the mod of the positions */
start ModofthePositions(b, p); /* It will always return a positive value for mod(b,p) */
return( b - p*floor(b/p) );
finish;
/* This function is to Create a Magic square when n is odd using MATLAB */
start OddMagicmatrixsquare(n);
L = repeat( T(1:n), 1, n );
M = repeat( 1:n, n ); /* or T(L) */
N = ModofthePositions(L+M-(n+3)/2, n); /*Formula to generate a magic square in matlab */
B = mod(L+2*M-2, n);
return( n*N + B + 1 );
finish;
/* The following is the main part */
If n=0 then return ( {. ., . .} ); /* no magic square exists */
else if n=1 then return ( {. ., . .} ); /* no magic square exists */
else if n=2 ( {. ., . .} ); /* no magic square exists */
else if n>=3
{ if mod(n,2)=1 then return( OddMagicmatrixsquare(n) ); /* n is odd */
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.