필터 지우기
필터 지우기

Given a matrix A = [2 5 7; 4 1 8], write a for loop that will replace all the even numbers with 0.

조회 수: 2 (최근 30일)
I'm looking for something using a for loop (probably nested) and possibly mod(A,2) to determine the even numbers
What I tried: It took me a while to figure out how to format mod, but once I did I started with: for b=mod(A,2) I think tried to add a logical function (such as b==0) but it kept giving me errors. The closest thing that I could write that made sense in my head was:
for b=mod(A,2);
if b==0
A(b)=0
end
end
I would then get the error: Subscript indices must either be real positive integers or logicals.
I also couldn't figure out how to size a matrix to be the same size as a different matrix.
  댓글 수: 3
Sydney
Sydney 2016년 10월 7일
It took me a while to figure out how to format mod, but once I did I started with: for b=mod(A,2) I think tried to add a logical function (such as b==0) but it kept giving me errors. The closest thing that I could write that made sense in my head was:
% code
for b=mod(A,2);
if b==0
A(b)=0
end
end
I would then get the error: Subscript indices must either be real positive integers or logicals.
I also couldn't figure out how to size a matrix to be the same size as a different matrix.

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

채택된 답변

Mohammad Haghighat
Mohammad Haghighat 2016년 10월 7일
This can be a solution using for loops:
[m,n] = size(A);
for i = 1:m
for j = 1:n
if mod(A(i,j),2) == 0
A(i,j) = 0;
end
end
end
  댓글 수: 2
James Tursa
James Tursa 2016년 10월 7일
This is obviously a homework post. It is discouraged to do homework problems for others on this forum. Helping OP with concepts, correcting their code, etc is all within the spirit of this forum. But doing the entire problem outright for them is not.
Sydney
Sydney 2016년 10월 7일
This problem is an exercise in a reading I had to do to understand a homework problem.

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2016년 10월 7일
A(rem(A,2)==0)=0;
or with loop
for ii = 1:numel(A)
if rem(A(ii),2) == 0
A(ii) == 0;
end
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by