Avoiding many if-Statetments in a for-loop
Mostrar comentarios más antiguos
Hello everyone :)
I would like to run a for-loop over a vector. What to do with each element in the vector depends on many if-else statements. I simplified it like this:
clear variables;
rng default;
V1 = rand(365,1);
V2 = rand(365,1);
V2 = V2 <= 0.5;
V3 = rand(365,1);
V3 = V3 <= 0.3;
Vresult = zeros(length(V1),1);
tstart = 1;
tend = length(V1);
for t = tstart:tend
if V2(t) == 1
if V3(t) == 1
Vresult(t) = do_stuff(V1(t));
else
Vresult(t) = do_different_stuff(V1(t));
end
else
if V3(t) == 1
Vresult(t) = do_even_different_stuff(V1(t));
else
Vresult(t) = do_even_more_different_stuff(V1(t))
end
end
end
function [var_out] = do_stuff(var_in)
var_out = var_in * 5;
end
function [var_out] = do_different_stuff(var_in)
var_out = var_in + 3;
end
function [var_out] = do_even_different_stuff(var_in)
var_out = var_in / 4;
end
function [var_out] = do_even_more_different_stuff(var_in)
var_out = var_in - 2;
end
With even more if-else conditions and more calculations per statement it gets really confusing and unreadable. And I feel like I'm writing the same code over and over again as only some parts of the code are different in each statement and other parts stay the same.
How can I make my code more efficient, easier to read and maintainable? Sorry if this should be common knowledge :D
3 comentarios
Adam Danz
el 11 de Dic. de 2019
Are those the actual local functions (do_stuff, etc...) or are they just demo functions? I ask because the if those are the actual functions this could be heavily simplified.
Kilian Helfenbein
el 11 de Dic. de 2019
Editada: Kilian Helfenbein
el 11 de Dic. de 2019
Adam Danz
el 11 de Dic. de 2019
Respuesta aceptada
Más respuestas (1)
Something like this would seem to do the job, off the top of my head, though I may be over-simplifying it...
case1 = V2 && V3;
case2 = V2 && ~V3;
case3 = ~V2 && V3;
case4 = ~V2 && ~V3;
Vresult( case1 ) = do_stuff( V1( case1 ) );
Vresult( case2 ) = do_different_stuff( V1( case2 ) );
Vresult( case3 ) = do_even_different_stuff( V1( case3 ) );
Vresult( case4 ) = do_even_more_different_stuff( V1( case4 ) );
Categorías
Más información sobre Get Started with MATLAB en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!