How to code a MEX file for a function with logical tests on array values

I have the following function coded as an m-file:
_______
function y = phiabs(x)
% returns log((e^|x| + 1)/(e^|x| - 1))
if x < 0
x = -x;
end
if (x >= 1e-12) && (x <= 30.)
z = exp(-x);
y = log((1. + z)/(1. - z));
elseif x > 30
y = 2. * exp(-x);
else
y = log(2./(x + 1e-100));
end
______
If I try to apply it to an array or matrix, the "if" tests give trouble. To code it as a MEX file would involve individual calls to log() and exp() via mexCallMATLAB() for each element. Is there a more efficient way?

 採用された回答

David
David 2014 年 4 月 3 日

0 投票

Solved my problem - used the C math library exp() and log() functions in the MEX .c file. Seemed like cheating to not call the Matlab functions, but it works.

その他の回答 (1 件)

Jan
Jan 2014 年 4 月 3 日
Instead of calling a MEX function, you could get rid of the problems occurring for the IF statement when processing arrays:
function y = phiabs(x)
x = abs(x);
y = zeros(size(x));
idx = (x > 30);
y(idx) = 2.0 * exp(-x(idx));
idx = ~idx & x >= 1e-12;
z = exp(-x(idx));
y(idx) = log((1 + z) ./ (1 - z));
idx = (x < 1e-12);
y(idx) = log(2 / (x(idx) + 1e-100));
end

カテゴリ

ヘルプ センター および File ExchangeWrite C Functions Callable from MATLAB (MEX Files) についてさらに検索

製品

タグ

質問済み:

2014 年 4 月 3 日

回答済み:

Jan
2014 年 4 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by