Videos
Basically say i needed to write some code for some grades and say if the grades were:
A: 90-100
B:80-90
C:70-80
How would i write an if statement with condition of the grade being between two numbers?
I find if-statements with one line of code in each condition annoyingly long for the task they perform. I came up with an alternative that works with most circumstances, and I was wondering if people think the following is acceptable code.
% Using if statements
if x>5
y = x;
elseif x<5
y = x^2;
else
y = 10;
end
disp(y)
% Using ifs and nonzero
ifs = [x,x^2,10];
y = nonzeros(ifs(x>5,x<5,x==5));
disp(y)The alternative is much shorter, and runs *slightly* faster, but is a little harder to read. Another example from a recent script is
% Using if statements
if nargin<3 || nargin>4
error('Function requires 3 or 4 input arguments');
elseif n<2
error('Number of segments must be at least 2');
elseif ~isinteger(n/2)
error('Number of segments must be a multiple of 2');
end
% Using ifs and nonzero
ifs = error('Function requires 3 or 4 input arguments');
ifs = [ifs,error('Number of segments must be at least 2')];
ifs = [ifs,error('Number of segments must be a multiple of 2')];
nonzeros(ifs(nargin<3||nargin>4,n<2,~isinteger(n/2)))Would using this method, with proper comments, be considered acceptable code, or would it just be too unusual for people to know how to read?
Thanks for your input.
There is no syntactic sugar for one-line if-statements in MatLab, but if your statement is really simple you could write it in one line.
I used to have one-line if-statements like that in my old project:
if (k < 1); k = 1; end;
In your case it'll look something like:
if a > b; foo = 'r'; else; foo = 'g'; end;
or, if you don't like semicolons
if a > b, foo = 'r'; else, foo = 'g'; end
Not as pretty as you may have expected, though.
Not as elegant as a C style ternary operator but you can take advantage of the fact that matlab will automatically cast logicals into doubles in this situation. So you can just multiply your desired result for true (r in this case) by your condition (a > b), and add that to the product of your desired result for false (i.e. g) with the not of your condition:
foo = (a > b)*c + (~(a > b))*d
so if we let c = 'r' and d = 'g' then all we need to do is cast foo back to a char at the end:
char(foo)
or
char((a > b)*'r' + ~(a > b)*'g')
Note that this will only work if c and d have the same dimensions (because of the +)...