overly convoluted elseif condition
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Bob Thompson
2019-11-15
You can replace all of them with a single statement and indexing.
if x>=1 & x<=4
y = p(x);
else
y = 1;
end
0 个评论
更多回答(2 个)
ME
2019-11-15
function y=gain(x)
for jj=1:4
p(jj)=1-jj/128;
end
if x<=4
y=p(x);
else
y=1;
end
end
I have assumed here that your final y==1 was supposed to assign y=1 if x is anything else that 1-4. If that is incorrect then just adjust that last part.
0 个评论
Steven Lord
2019-11-15
The approaches suggested by Bob Nbob and ME each work if the only values x can take in the range [1, 4] are integer values. If it can take values like 2.5 or pi, I'd use ismember.
% Sample data
x = [1, 2, 2.5 pi, 4, 42]
p = x.^2 + x
% Locate values of x that are 1, 2, 3, or 4
M = ismember(x, 1:4)
% Start y off with the default value of 1 and the right size (the same size as x)
y = ones(size(x))
% Fill in the elements of y where x is 1, 2, 3, or 4 with the right elements of p
y(M) = p(M)
% Let's do something with the other elements too to illustrate the technique
y(~M) = x(~M)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!