Modify the code from the previous example

clear, close all;
% Activity problem 6
% First example. With a loop, no ligical indexing.
N=6;
%NxN magic square
A=magic(N);
%Initialise B to be the same size as A with ones
B=ones(N);
%Set B to one where A is divisible by 3
%Loop over all elements
for row=1:N
for col=1:N
%Get current elemnet's value.
value=A(row,col);
%Is it a multiple of 3:
if (mod(value,3)==0)
B(row,col)=0;
end
end
end
disp(B)
% Second example, use logical indexing.
N=6;
A=magic(N)
B=ones(N);
indices=mod(A,3)==0;
B(indices)=0;
disp(B)
% part c
B(mod(A,3)==0)=0;
Now, based on the practice above, modify the code so that it starts with a magic square of size 5x5 and produces a second array that has a value of one where the magic square element is odd and a value of 2 where the corresponding magic square element is even.

5 Kommentare

Walter Roberson
Walter Roberson am 19 Feb. 2019
What is your question?
Hint: if C is a value that is either 0 or 1, then A + (B-A)*C will give a value that is either A or B.
Abigail McGahey
Abigail McGahey am 19 Feb. 2019
i need to change to above code to follow the following criteria: it starts with a magic square of size 5x5 and produces a second array that has a value of one where the magic square element is odd and a value of 2 where the corresponding magic square element is even.
Walter Roberson
Walter Roberson am 19 Feb. 2019
Bearbeitet: Walter Roberson am 19 Feb. 2019
Your code builds an NxN magic square. If you want a 5 x 5 square specifically, then perhaps you should change N to be 5.
Note that restating a problem is not asking a question. A question might be something like,
"When I ran this code, on line 17, which is ...., it tells me that I have a subscript out of range. Could someone explain what that means?"
Abigail McGahey
Abigail McGahey am 19 Feb. 2019
okay, so to be more clear, I am struggling to figure out how to replace the odd elements with one and the even elements with the value of two.
Walter Roberson
Walter Roberson am 22 Feb. 2019
"I am struggling" is not a question. A question might be something like how to write loops, or how to detect that a value is odd or even.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Pranjal Priyadarshi
Pranjal Priyadarshi am 22 Feb. 2019

0 Stimmen

The code below takes a magic square of size 6 and replaces the even elements with 2 and replaces the odd elements with 1.
N=6;
A=magic(N);
evenindex=(mod(A,2) == 0); %finds the index for even elements
finalans=A;
finalans(evenindex)=2; %replaces even elements with 2
finalans(~evenindex)=1; %replaces odd elements with value 1
disp(A);
disp(finalans);

Gefragt:

am 19 Feb. 2019

Kommentiert:

am 22 Feb. 2019

Community Treasure Hunt

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

Start Hunting!

Translated by