Un si La declaración puede ir seguida de uno (o más) opcional. elseif … y un demás declaración, que es muy útil para probar varias condiciones.
Al usar declaraciones if … elseif … else, hay algunos puntos a tener en cuenta:
-
Un if puede tener cero o uno más y debe ir después de cualquier elseif.
-
Un if puede tener de cero a muchos elseif y deben venir antes que el else.
-
Una vez que un else if tiene éxito, no se probará ninguno de los elseif o elseif restantes.
Sintaxis
if <expression 1> % Executes when the expression 1 is true <statement(s)> elseif <expression 2> % Executes when the boolean expression 2 is true <statement(s)> Elseif <expression 3> % Executes when the boolean expression 3 is true <statement(s)> else % executes when the none of the above condition is true <statement(s)> end
Ejemplo
Cree un archivo de secuencia de comandos y escriba el siguiente código en él:
a = 100; %check the boolean condition if a == 10 % if condition is true then print the following fprintf('Value of a is 10n' ); elseif( a == 20 ) % if else if condition is true fprintf('Value of a is 20n' ); elseif a == 30 % if else if condition is true fprintf('Value of a is 30n' ); else % if none of the conditions is true ' fprintf('None of the values are matchingn'); fprintf('Exact value of a is: %dn', a ); end
Cuando el código anterior se compila y ejecuta, produce el siguiente resultado:
None of the values are matching Exact value of a is: 100
matlab_decisions.htm