Why doesn't my script work. I try to create a vector in dependecy of variable without a loop. I'm not sure how i have to define the vector before the if cases
Afficher commentaires plus anciens
if true
% code
z=0:1:4000;
g_1=0;
g_2=0;
v(z)=NaN(length(z));
for b=1:length(z)
if z<2000
v(z)=1500+z*g_1;
elseif z>=2000
v(z)=2000+z*g_2;
end
end
end
1 commentaire
Stephen23
le 16 Nov 2017
See KL's answer for a much simpler solution.
Réponse acceptée
Plus de réponses (1)
KL
le 16 Nov 2017
No need for a loop, use logical indexing. Here's a better way to write that,
indx = z<2000;
v(indx) = 1500+z(indx)*g_1;
v(~indx)=2000+z(~indx)*g_2;
4 commentaires
Stephen23
le 16 Nov 2017
+1 simple, and very good use of MATLAB.
KL
le 16 Nov 2017
Thanks Stephen:)
Sebastian
le 16 Nov 2017
Jan
le 25 Nov 2017
+1. Or shorter:
idx = (z >= 2000);
v = 1500 + 500 * idx + z .* (g_1 .* (~idx) + g_2 .* idx);
With reordering the terms this is running 3 times faster:
v = (1500 + z .* g_1) .* ~idx + (2000 + z.* g_2) .* idx;
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!