Can we use elseif in a conditional statement this much time?%shortest path selection algorithm for R1

2 visualizaciones (últimos 30 días)
%shortest path selection algorithm for R1
if YR11>YR12
small_dist_R11=YR12
elseif YR12>YR11
small_dist_R11=YR11
elseif small_dist_R11>YR13
small_dist_R12=YR13
elseif YR13>small_dist_R11
small_dist_R12=small_dist_R11
elseif small_dist_R12>YR14
small_dist_R13=YR14
elseif YR14>small_dist_R12
small_dist_R13=small_dist_R12
elseif small_dist_R13>YR15
small_dist_R14=YR15
else
small_dist_R14=small_dist_R13
end

Respuesta aceptada

Guillaume
Guillaume el 4 de Dic. de 2015
You can use as many elseif as you want. Whether it is wise, probably not as it makes it harder to understand the code, particularly if there's no comment to explain what is going (hint!)
Note that:
if A > B
minimum = B
elseif B > A
minimum = A
end
is more or less the same as
minimum = min(A, B)
The only difference is when A == B. Your code does not assign a value to minimum (so the variable does not even get created), whereas min does. Whether or not that was your intention or it's a bug in your code is unknown. If it was the intention then I would have expected a comment to state it (hint! hint!) so the question does not need asking.
Also, because of the elseifs your code will only calculate small_dist_R12 if it does not set a value for small_dist_R11 (so if YR11 == YR12), so presumably small_dist_R11 already has a value, otherwise it's a bug (if it's not, again, a comment is missing). Same for the other small_dist, they only get calculated if the previous minimum has not been calculated.
All in all, I think you meant:
small_dist_R11 = min(YR11, YR12);
small_dist_R12 = min(small_dist_R11, YR13);
small_dist_R13 = min(small_dist_R12, YR14);
small_dist_R14 = min(small_dist_R14, YR15);
if you really meant the code in your elseifs, then as I said comments are necessary.
Finally, if you are only interested in the final small_dist, and your YR are scalar:
small_dist_R14 = min([YR11 YR12 YR13 YR14]);

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by