How to replace a for loop that contains an if statement?

조회 수: 3 (최근 30일)
gsourop 2021년 2월 1일
편집: Star Strider 2021년 2월 1일
Dear everyone,
I have 2 vectors with random numbers
A = -5 + (5+5)*rand(10,1);
B = -5 + (5+5)*rand(10,1);
and based on the sign of each pair, I want to create a third vector ('C') that will get the respective value of B, if A(i)*B(i)>0 and zero, otherwise. Is there any better way to employ this rather than using a for loop, such as:
for i = 1:10
if A(i)*B(i)>0
C(i) = B(i);
else
C(i) = 0;
end
end
A solution on the basis of not creating a third vector ('C') and overwritting B is also welcome, such as
for i = 1:10
if A(i)*B(i)<0
B(i) = 0;
end
end
Thank you in advance!

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

채택된 답변

Star Strider 2021년 2월 1일
편집: Star Strider 2021년 2월 1일
One of these should do what you want:
A = -5 + (5+5)*rand(10,1);
B = -5 + (5+5)*rand(10,1);
LogicalReference = (A.*B)>0; % Logical Vector
DesiredResult = LogicalReference.*B; % Either Will Work Here
.

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

추가 답변 (1개)

KALYAN ACHARJYA 2021년 2월 1일
C=B.*(A.*B>0)

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by