How can I write this exponential function in matlab?

75 ビュー (過去 30 日間)
rohail khan
rohail khan 2018 年 3 月 28 日
コメント済み: Walter Roberson 2021 年 11 月 23 日
hi, please can anyone help me write the following functions in matlab?

採用された回答

Walter Roberson
Walter Roberson 2018 年 3 月 28 日
f = @(x) exp(-x.^2/4) .* cos(2*pi*x);
g = @(x) exp(x) .* (x <= 0) + sin(2*pi*x)./max(x,realmin) .* (x>0);
  3 件のコメント
rohail khan
rohail khan 2018 年 3 月 31 日
please can you explain the meaning of : max(x,realmin) in your code
Walter Roberson
Walter Roberson 2018 年 3 月 31 日
Suppose x is 0 exactly. Then sin(2*pi*x)/x would be 0/0 which would be NaN. The (x>0) after that would multiply the NaN by 0, but NaN times anything is NaN, so you cannot use logical computations like this to mask out a NaN result.
Instead you need to avoid the NaN result. One way of doing that is to detect that you are dividing by 0 and to substitute a different value that is not 0.
The expression max(x,realmin) is equivalent to a vectorized version of
if x <= realmin
temp = realmin;
else
temp = x;
end
realmin is about 1E-308 -- a very small value but not 0. So max(x,realmin) substitutes the positive value realmin for all negative and 0 values, which is enough to prevent division by 0.
Another way of coding it would have been
sin(2*pi*x)./(x + (x == 0)) .* (x>0);
x == 0 would be 0 for all non-zero x and so would not change any x that was not 0. x == 0 would be 1 for x of 0, so for the case of any non-zero value (x+(x==0)) would be the same as the value and for zero exactly it would be 1, thereby preventing division by 0.

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

その他の回答 (1 件)

Rajulapati Naveen
Rajulapati Naveen 2021 年 11 月 23 日
f = @(x) exp(-x.^2/4) .* cos(2*pi*x); g = @(x) exp(x) .* (x <= 0) + sin(2*pi*x)./max(x,realmin) .* (x>0);

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by