MATLAB: Overly convoluted elseif condition

elseiffor looploop

Hi, I am writing a code that uses too many else if conditions.I am wondering is there an easy way to that.
function y=gain(x)
for jj=1:4
p(jj)=1-jj/128;
end
if x==1
y=p(1);
elseif x==2
y=p(2)
elseif x==3
y=p(3);
elseif x==4
y=p(4);
else y==1;
end

Best Answer

You can replace all of them with a single statement and indexing.
if x>=1 & x<=4
y = p(x);
else
y = 1;
end