How to create a conditional symbolic function?
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Oscar
am 5 Dez. 2014
Beantwortet: Walter Roberson
am 26 Aug. 2018
Something like:
syms x
f(x) = sym('f(x)');
if (x>0 && x<=500)
f(x)=x^3;
elseif(x>500 && x<=1800)
f(x)=x^4;
else
fx(x)=x^2+100;
end
0 Kommentare
Akzeptierte Antwort
John Mahoney
am 5 Dez. 2014
Hi Oscar,
How about this?
syms x
% Define each subfunction
f1 = x^3;
f2 = x^4;
f3 = x^2 + 100;
% Chop undesired ranges using heaviside / step function.
f1 = f1 * heaviside(x - 0) * (1 - heaviside(x - 500));
f2 = f2 * heaviside(x - 500) * (1 - heaviside(x - 1800));
f3 = f3 * (1 - heaviside(x - 0)) + f3 * heaviside(x - 1800);
% Add em up
f = f1 + f2 + f3;
% I plot the logarithm here since plotting f shows only the contribution from the dominant f2.
flog = log(f);
ezplot(flog, [-500, 3000])
2 Kommentare
Weitere Antworten (1)
Walter Roberson
am 26 Aug. 2018
The question was asked in 2014. Since that time, piecewise() was added in R2016b https://www.mathworks.com/help/symbolic/piecewise.html
Before that, you had to invoke MuPad's piecewise function using feval or evalin. I have posted the code in the past.
You have to be quite careful using Heaviside for this purpose, as Heaviside is not defined when the input expression is exactly 0. There are several different conventions for Heaviside(0), with it commonly being defined as 0, or 1, or 1/2, and sometimes even defined as infinity. MATLAB implemented sympref() to allow user control of Heaviside(0)
When you differentiate Heaviside you should get the Dirac delta distribution (which is not strictly a function.) But if you custom defined Heaviside(0) then you need to think carefully about whether dirac() is appropriate for the situation.
When you convert a piece wise description of a function to Heaviside calls, chances are that you need to toss in a dirac() for each boundary point to define the behavior right at the boundary correctly, especially for integration purposes.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Assumptions finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!