MATLAB: Nested if else statements

nested if else

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?

Best Answer

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')
else
disp('x is a integer value between 3 and 6')
end
elseif x < 3
disp('x is less than 6')
end
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 ~isempty(grade)
if grade > 70
disp('Assignment passed!')
else
disp('Assignment failed!')
end
else
disp('No grade found for this assignment!')
end
Here's another example in which we have to use the nesting in order to check for cases where a blank grade was given.
Related Question