# How to reduce vectors sizes if an element in a parent vector equals to zero without accessing for loop

조회 수: 1 (최근 30일)
George Ansari 2017년 8월 7일
댓글: George Ansari 2017년 8월 8일
Dear all,
I have the following code, is there a way to do the same thing but without for loop?
P_max = [100 150 200];
B = [1 2 3];
Pg = [90 150 150];
P=P_max - Pg;
for i=1:length(P_max)
if (P(i) == 0)
B(:,i) = [];
Pg(:,i) = [];
P_max(:,i) = [];
end
end
Thanks! George.

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

### 채택된 답변

Hi George,
Yes, there's a very efficient way to do this in Matlab without loops. Get the indices of all P = 0 like this:
ind = P==0;
Then remove the corresponding elements in B, Pg, and P_Max like this:
B(ind) = [];
##### 댓글 수: 2없음 표시없음 숨기기
A small note: You're doing a good thing by removing the loop in this case. But when you do need to use loops, try not to use the variable i or j, because they're both built-in variable names in Matlab meaning sqrt(-1). Instead, it's common practice to use for k = ...
George Ansari 2017년 8월 8일
Thanks a lot!

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

### 카테고리

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