Modify the code from the previous example
조회 수: 2 (최근 30일)
이전 댓글 표시
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
Walter Roberson
2019년 2월 22일
"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.
답변 (1개)
Pranjal Priyadarshi
2019년 2월 22일
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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!