How to create a conditional symbolic function?

11 ビュー (過去 30 日間)
Oscar
Oscar 2014 年 12 月 5 日
回答済み: Walter Roberson 2018 年 8 月 26 日
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

採用された回答

John Mahoney
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 件のコメント
Oscar
Oscar 2014 年 12 月 5 日
Excellent
moh pouladin
moh pouladin 2018 年 8 月 26 日
Based on your answer:
f(0)=50
But it have to equal 100.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
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.

カテゴリ

Help Center および File ExchangeAssumptions についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by