How to make piece-wise function accept single variables and vectors
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
VBBV
le 24 Fév 2023
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 commentaires
VBBV
le 24 Fév 2023
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
le 24 Fév 2023
Probably one should avoid shadowing the symbolic toolbox function:
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!