How to make piece-wise function accept single variables and vectors
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
VBBV
2023-2-24
x = 2:1000;
y = piecewise(x)
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 个评论
VBBV
2023-2-24
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.
Stephen23
2023-2-24
Probably one should avoid shadowing the symbolic toolbox function:
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!