How to reduce vectors sizes if an element in a parent vector equals to zero without accessing for loop
1 次查看(过去 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.
0 个评论
采纳的回答
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
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!