How to make piece-wise function accept single variables and vectors

I have a piece-wise function that can take a single variable and produce my desired output. However, the problem I am having is when there are vectors instead of single variables. For example, it will not accept vectors (0:1:10) or (1 2 3 4 5), where the code produces no output at all. I have put the x. so that it would do the operations for every variable in a given vector, but it has no effect.
function y = piecewise(x)
if (x>0) & (x<=120) % for 0 < x <= 120
y = ((800*x.^3)-(13.68*(10^6)*x)-(2.5*x.^4)) % Use this equation
elseif (x>120) & (x<=240) % for 120 < x <= 240
y = ((800*x.^3)-(13.68*(10^6)*x)-(2.5*x.^4)+2.5*(x-120)^4) % Use this equation
elseif (x>240) & (x<=360) % for 240 < x <= 360
y = ((800*x.^3)-(13.68*(10^6)*x)-(2.5*x.^4)+2.5*(x-120)^4+600*(x-240)^3) % Use this equation
end

 Accepted Answer

x = 2:1000;
y = piecewise(x)
y = 1×359
1.0e+08 * -0.2735 -0.4102 -0.5467 -0.6830 -0.8191 -0.9549 -1.0904 -1.2255 -1.3602 -1.4945 -1.6283 -1.7615 -1.8942 -2.0263 -2.1577 -2.2884 -2.4184 -2.5476 -2.6760 -2.8036 -2.9303 -3.0561 -3.1809 -3.3048 -3.4276 -3.5494 -3.6702 -3.7898 -3.9082 -4.0256
function y = piecewise(x)
for k = 1:length(x)
if (x(k)>0) & (x(k)<=120) % for 0 < x <= 120
y(k) = ((800*x(k)^3)-(13.68*(10^6)*x(k))-(2.5*x(k)^4)); % Use this equation
elseif (x(k)>120) & (x(k)<=240) % for 120 < x <= 240
y(k) = ((800*x(k)^3)-(13.68*(10^6)*x(k))-(2.5*x(k)^4)+2.5*(x(k)-120)^4); % Use this equation
elseif (x(k)>240) & (x(k)<=360) % for 240 < x <= 360
y(k) = ((800*x(k)^3)-(13.68*(10^6)*x(k))-(2.5*x(k)^4)+2.5*(x(k)-120)^4+600*(x(k)-240)^3); % Use this equation
end
end
end

2 Comments

you can use a for loop inside the function, and access the elements inside the input vector. However, when you dont use for loop it will compare the condition only once, which when not satisfied will result in error.

Sign in to comment.

More Answers (0)

Products

Release

R2022b

Asked:

on 24 Feb 2023

Commented:

on 24 Feb 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!