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

2 ビュー (過去 30 日間)
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.

採用された回答

Chad Greene
Chad Greene 2017 年 8 月 7 日
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 件のコメント
Chad Greene
Chad Greene 2017 年 8 月 7 日
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 = ...

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by