nested if else statements
383 visualizzazioni (ultimi 30 giorni)
Can someone write an example of a nested if else statement? matlab keeps underlining the 'else' when I try to write a nested 'if else' statement telling me the syntax is wrong.
Also, where do I put the 'end' for each of the 'if else' statements?
Evan il 25 Lug 2013
Modificato: Evan il 25 Lug 2013
x = 5.5
if x > 6
disp('x is greater than 6')
elseif x >= 3 && x <= 6
if mod(x,1) ~= 0
disp('x is a non-integer value between 3 and 6')
disp('x is a integer value between 3 and 6')
elseif x < 3
disp('x is less than 6')
The above code checks to see what range x falls in, then enters an if/else statement that determines whether it is evenly divisible by one. If not, this means x is not an integer value and the corresponding text is displayed. Here, you could get rid of the nesting if you liked by using statements like elseif x >=3 && x <= 6 && mod(x,1) ~= 0, but eventually it would get messy and difficult to read.
%grade = ;
grade = 75;
if grade > 70
disp('No grade found for this assignment!')
Here's another example in which we have to use the nesting in order to check for cases where a blank grade was given.
Più risposte (4)
Sohrab Abedini il 27 Dic 2015
Modificato: Sohrab Abedini il 27 Dic 2015
The examples were great. However, I could not still find a solution to this problem of mine: I don't know how to write it in matlab code->
if n=4 then -> c=2, d=3 or c=3 , d=2.
I wondering if writing "or" is acceptable in result statement. it seems wrong but I have to do it somehow. --- The actual problem is changing a 2nd rank Tensor to a 4th rank tensor through Voigt mapping. which is quite easy vise versa and so difficult in this way. I might be able to solve it if I understand to write "or" or sth like that in if statement.
Nava Subedi il 26 Nov 2016
Modificato: Stephen23 il 26 Nov 2016
Can someone help me to what is wrong with my code:
function [l, m, n] = sort3([a b c])
if a>=b && a>=c
l = c;
l = b;
else l = a;
elseif b>=a && b>=c
m = c;
m = a;
else m = b;
else c>=a && c>=b
n = b;
n = a;
else n = c;
I am trying to write nested if statement.