How to create a conditional symbolic function?
조회 수: 9 (최근 30일)
이전 댓글 표시
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
채택된 답변
John Mahoney
2014년 12월 5일
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
추가 답변 (1개)
Walter Roberson
2018년 8월 26일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Assumptions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!