How to reduce vectors sizes if an element in a parent vector equals to zero without accessing for loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
George Ansari
le 7 Août 2017
Commenté : George Ansari
le 8 Août 2017
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 commentaires
Réponse acceptée
Chad Greene
le 7 Août 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 commentaires
Chad Greene
le 7 Août 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 = ...
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!