how to code magic square without the built in command

10 visualizaciones (últimos 30 días)
Antrea Plastira
Antrea Plastira el 12 de Oct. de 2022
Respondida: Sunny Choudhary el 7 de Jun. de 2023
I want to write a code which generates the magic square NxN. I have a problem inserting the rules that apply to the magic square. these are the rules:
  1. Ask the user for an odd number
  2. Create an n by n array.
  3. Follow these steps to create a magic square.
a. Place a 1 in the middle of the first row.
b. Subtract 1 from the row and add 1 to the column.
i. If possible place the next number at that position.
ii. If not possible, follow these steps.
If in row -1, then change to last row
If in last column change to first column
If blocked, then drop down to next row (from original position)
if in the upper right corner, then drop down to next row.
  1. Print the array
my code so far:
n = input('give dimension number for magic square: ');
M = zeros(n,n);
%position for number 1
M(floor(n/2),n-1) = 1;
  1 comentario
David Hill
David Hill el 12 de Oct. de 2022
Rules seem straight forward. Continue coding (using indexing) and ask a specific question.

Iniciar sesión para comentar.

Respuestas (1)

Sunny Choudhary
Sunny Choudhary el 7 de Jun. de 2023
Sure here's the working code:
% Ask the user for an odd number
n = input('Enter an odd integer for the dimension of the magic square: ');
% Check if n is odd
if mod(n, 2) == 0
error('Error: You entered an even number. Please enter an odd number.');
end
% Create an n by n array of zeros
magic_square = zeros(n);
% Place a 1 in the middle of the first row
row = 1;
col = ceil(n/2);
magic_square(row, col) = 1;
% Populate the rest of the magic square
for num = 2:n^2 % start from 2 because 1 is already in the middle of the first row
% Subtract 1 from the row and add 1 to the column
row = row - 1;
col = col + 1;
% Check if the new position is out of bounds
if row < 1 && col > n % upper right corner
row = 2;
col = n;
elseif row < 1 % row out of bounds
row = n;
elseif col > n % column out of bounds
col = 1;
elseif magic_square(row, col) ~= 0 % blocked
row = row + 2;
col = col - 1;
% Check if the new position is out of bounds
if row > n
row = row - n;
elseif col < 1
col = col + n;
end
end
% Place the number at the new position
magic_square(row, col) = num;
end
% Print the magic square
disp(magic_square)

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by