Ältere Kommentare anzeigen
Hi just a simple question, Which is a better use, 'if' or 'switch'? Thanx P
1 Kommentar
Jan
am 20 Sep. 2011
Please add the relevant part of the code to your question. without seeing any details a decision is not possible.
Akzeptierte Antwort
Weitere Antworten (1)
Walter Roberson
am 20 Sep. 2011
2 Stimmen
Switch evaluates the value of the switch portion, and then it evaluates each case expression in the list until finally one of the cases matches the switch value. This is pretty much the same complexity as the corresponding if/elseif cascade.
Most people write code as if the switch cases must be constants, but that is not the case in MATLAB: they can be full expressions with function calls and all.
This needs to be compared to other computer languages such as C, in which the case labels do need to be constants. In those other languages, it is possible to do preprocessing such that the time required to decide which branch to use is decided in constant time (or near constant time.) In those languages, switch is more efficient than if/elseif chains.
In MATLAB, if/elseif chains are often able to optimize groups of cases by using extended logical conditions with && and || operators; it is difficult to do that kind of optimization using switch.
1 Kommentar
PChoppala
am 20 Sep. 2011
Kategorien
Mehr zu Structures finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!