Clear Filters
Clear Filters

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

1 view (last 30 days)
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.

Accepted Answer

Chad Greene
Chad Greene on 7 Aug 2017
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 Comments
Chad Greene
Chad Greene on 7 Aug 2017
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 = ...

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!