piecewise function evaluation using if-else statement
Mostra commenti meno recenti
Hi, I have this code for a 'piecewise function' to be evaluated.
t = -10:0.01:10;
if t<0
F(1,:) = 2.*t;
elseif t<8
F(1,:) = sqrt(t);
else F(1,:) = t+1;
end
I was wondering why the output is different from the one I was expecting.
Expected output: all numbers below 0 must be twice that number.
Output:
-9 -8.99000000000000 -8.98000000000000 -8.97000000000000 -8.96000000000000 -8.95000000000000 -8.94000000000000 -8.93000000000000 -8.92000000000000 -8.91000000000000 -8.90000000000000 -8.89000000000000 -8.88000000000000 -8.87000000000000 -8.86000000000000…….
Risposta accettata
Più risposte (2)
Adam
il 16 Mar 2015
You can't use an if statement on a vector (or rather you can, but it is usually not the effect you wish to achieve, as in this case).
if t < 0
will test if the entire vector t is less than zero. It isn't. The else will test if the entire vector is less than 8. It isn't. Therefore the final else clause will be the one that kicks in and simply add 1 to all elements.
You can use vectorisation to achieve this as e.g.
t = -10:0.01:10;
F = t + 1;
F( t < 0 ) = 2 .* t( t < 0 );
F( t >= 0 & t < 8 ) = sqrt( t( t >= 0 & t < 8 ) );
Personally I would probably factor out that ugly condition that is used twice in the same line, but that is just semantics and personal preference.
1 Commento
cgo
il 16 Mar 2015
Sally Al Khamees
il 21 Feb 2017
If you have R2016b and the Symbolic Math Toolbox installed, you can just use the piecewise function:
t = -10:0.01:10;
syms y(t);
y(t) = piecewise(t<0, 2*t, 0 <= t <= 8, sqrt(t), t+1);
fplot(y,t)

Categorie
Scopri di più su Conversion Between Symbolic and Numeric in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!