overly convoluted elseif condition
1 view (last 30 days)
Hi, I am writing a code that uses too many else if conditions.I am wondering is there an easy way to that.
More Answers (2)
ME on 15 Nov 2019
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.
Steven Lord on 15 Nov 2019
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)