Clear Filters
Clear Filters

Call a Python function inside a MATLAB loop

5 views (last 30 days)
Sim
Sim on 5 Aug 2024
Commented: Sim on 7 Aug 2024
In a Matlab script, is there a way to call a Python function, in loop for, in such a way that at every iteration the inputs of the Python function are different?
This is my case, where the arrays "a" and "b" are always different, and they return, obviously, different outputs:
% My Python function
import numpy as np
from scipy import stats
a = [7, 42, 61, 81, 115, 137, 80, 100, 121, 140, 127, 110, 81, 39, 59, 45, 38, 32, 29, 27, 35, 25, 22, 20, 19, 14, 12, 9, 8, 6, 3, 2, 2, 0, 0, 1, 0, 1, 0, 0];
b = a;
rng = np.random.default_rng()
method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
res = stats.anderson_ksamp([a,b], method=method)
print(res.statistic)
print(res.critical_values)
print(res.pvalue)
To add more details, I would like to have something like this in Matlab:
% Call my Python function inside a MATLAB loop
for i = 1 : 10
a = randi([1 100],1,50);
b = randi([1 100],1,50);
out = call_my_python_function_here(a,b);
end
  6 Comments
dpb
dpb on 5 Aug 2024
I don't have Python installed so can't play at it, but looks to me like the basics of your function wish in MATLAB would simply be something about like
function stats=anderson(a,b)
stats=py.scipy.stats.anderson_ksamp([a,b]);
end
and you'd simply call it as any other MATLAB function.
The doc implies you don't need to import stuff (although you could for shorthand if were referencing the same module repeatedly) but just prefix with the py.module and it will resolve the name itself.
I ignored whatever you're trying to do with the RNG; you can deal with it as you see fit/need but if I were generating RNGs besides, I'd certainly call the native MATLAB version there, not pass that off to Python.

Sign in to comment.

Answers (2)

Pavan Sahith
Pavan Sahith on 5 Aug 2024
Edited: Pavan Sahith on 5 Aug 2024
Hello Sim,
To call a Python function within a MATLAB loop with different inputs at each iteration, define your Python function and save it in a file, say my_python_function.py,ensure that your Python file is in the current working directory or the Python path.
In MATLAB, you can try using a similar code to call a Python function inside a loop
% Loop to call the Python function with different inputs
for i = 1:10
% Generate random arrays a and b
a = randi([1 100], 1, 50);
b = randi([1 100], 1, 50);
% Convert MATLAB arrays to Python lists
py_a = py.list(a);
py_b = py.list(b);
% Call the Python function
result = py.my_python_function.anderson_ksamp_test(py_a, py_b);
% Extract results from the Python function output
statistic = double(result{1});
critical_values = double(result{2});
pvalue = double(result{3});
% Display the results
fprintf('Iteration %d:\n', i);
fprintf('Statistic: %f\n', statistic);
fprintf('Critical Values: %s\n', mat2str(critical_values));
fprintf('P-value: %f\n', pvalue);
end
Here are some useful resources from MathWorks documentation that provide more details on how to integrate MATLAB and Python:
Hope this helps you in moving forward
  11 Comments
Walter Roberson
Walter Roberson on 7 Aug 2024
I know very very little about python, sorry.
Sim
Sim on 7 Aug 2024
Thanks @dpb and @Walter, I greatly appreciate your comments and help, thanks :-)

Sign in to comment.


dpb
dpb on 7 Aug 2024
Using <FEX Submittal> with your example dummy data, it generated the exact same statistic without all the mucking around with Python...
>> X=[[x.' ones(size(x)).'];[x.' 2*ones(size(x)).']]; % data with grouping variable 2nd column
AnDarksamtest(X)
K-sample Anderson-Darling Test
----------------------------------------------------------------------------
Number of samples: 2
Sample sizes: 10 10
Total number of observations: 20
Number of ties (identical values): 13
Mean of the Anderson-Darling rank statistic: 1
Standard deviation of the Anderson-Darling rank statistic: 0.6962062
----------------------------------------------------------------------------
Not adjusted for ties.
----------------------------------------------------------------------------
Anderson-Darling rank statistic: 0.0000000
Standardized Anderson-Darling rank statistic: -1.4363561
Probability associated to the Anderson-Darling rank statistic = 0.8963729
...
It looks to be well done, theoretically and is completely documented in the file as to how is computed, including the interpolation to return the critical values...
  5 Comments
dpb
dpb on 7 Aug 2024
The critical values for A-D are/were derived by simulation, not theoretically and any software implementation is using some sort of interpolation or lookup from those. It's quite possible internal to the Python implementation the case of identical distributions is special-cased and returns the integer unity value for that reason.
The interpolation technique used in the FEX submission is at least documented and you can figure out by comparison to the tables if it is breaking down near boundaries (which wouldn't be too surprising if so). Being as that is the case, it's likely the original tables don't go to the extreme with what is, in this case a very small sample size of only 10 elements and so exact values from the published table(s) may not be available for the specific case.
"...especially when reviewers pointed towards those values, in other tests, criticizing them a lot..."
Who/where might that be? On the Python or FEX side? I'd take the open version that can look at in detail over one I couldn't see; I'm not actually sure about what the "right" answer would be for the case without more consideration; it's been too long since I really studied it.
Sim
Sim on 7 Aug 2024
Yes, it might be something related to the table... Right...
About the reviewers, well, they were "from" a journal of the Nature Portfolio..
Yes, it is wiser to take an open version, to be then able to check what you are doing :-)

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!