how to code magic square without the built in command

조회 수: 10 (최근 30일)
Antrea Plastira
Antrea Plastira 2022년 10월 12일
답변: Sunny Choudhary 2023년 6월 7일
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
David Hill
David Hill 2022년 10월 12일
Rules seem straight forward. Continue coding (using indexing) and ask a specific question.

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

답변 (1개)

Sunny Choudhary
Sunny Choudhary 2023년 6월 7일
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)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by