User-defined matlab function does not return the right result when run from Python
6 ビュー (過去 30 日間)
古いコメントを表示
Hi everyone,
I wrote a function in Matlab R2020b then run it in Python using Matlab Engine API. However, for the same function arguments, the result returned from Python is different from the result returned by running the function in Matlab. The function is the following
function P = P_sinr(M,N_users,gamma_th,rho)
% Notice that this function is only used to calculate the probability
% that the SINR is larger than threshold in the GRANT-BASED segment
ratio = gamma_th/rho;
K = floor(N_users - 1);
P = 0;
for p = 0:1:M-K-1
P = P + exp(-ratio)*1/factorial(p)*ratio^p;
end
end
I tried to run it with M = 50, N_users = 20, gamma_th = 6.309, rho = 1.2589. Matlab returns 1, which is correct. However, Python returns 0, which is incorrect.
Any help will be appreciated.
2 件のコメント
Jan
2022 年 9 月 15 日
Please post the code you use to call this from Python. Maybe you provide some integer types instead of doubles? Or you catch the wrong output?
A more efficient version of the function:
function P = P_sinr(M, N_users, gamma_th, rho)
% Notice that this function is only used to calculate the probability
% that the SINR is larger than threshold in the GRANT-BASED segment
ratio = gamma_th / rho;
K = floor(N_users - 1);
P = 0;
c = exp(-ratio);
f = 1;
r = 1;
for p = 0:M-K-1
P = P + c / f * r;
f = f * (p + 1); % factorial
r = r * ratio; % ratio^p
end
end
回答 (1 件)
Udit06
2024 年 2 月 19 日
Hi,
Here is the python code to call the P_sinr function written in MATLAB.
% NOTE: This is a python code, hence putting the code in the block comment.
%{
import matlab.engine
eng=matlab.engine.start_matlab()
eng.addpath(r'path_to_your_matlab_function', nargout=0)
%CASE 1: Parameters = 50, 20, 6.309, 1.2589
eng.P_sinr(50, 20, 6.309, 1.2589)
%CASE 2: Parameters = 50.0, 20.0, 6.309, 1.2589
eng.P_sinr(eng.double(50), eng.double(20), eng.double(6.309), eng.double(1.2589))
%}
In Case 1, the result comes out to be 0, while in the Case 2, the result comes out to be approximately equal to 1. This is because of the difference in default numeric types in MATLAB and Python. The default numeric type in case of MATLAB is 'double-precision floating point' while it is 'int' in case of Python.
This can be confirmed by running the class function in MATLAB and type(50) command in python
class(50)
Refer to the following MathWorks documentation for more details regarding the default numeric type in MATLAB.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Call MATLAB from Python についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!