Introduction.
I have the following Python function, which is saved as “anderson_darling.py”:
def ADtest(a,b):
rng = np.random.default_rng()
method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
res = stats.anderson_ksamp([a,b], method=method)
print(a)
print(b)
print(res.statistic)
print(res.critical_values)
print(res.pvalue)
if __name__ == "__main__":
import sys
import numpy as np
from scipy import stats
input_list1 = list(map(int, sys.argv[1].strip('[]').split(',')))
input_list2 = list(map(int, sys.argv[2].strip('[]').split(',')))
a = np.array(input_list1)
b = np.array(input_list2)
ADtest(a,b)
To run this file, I open a Terminal (throgh Visual Studio Code, but this is not relevant), and I give the following command:
(base) xyz@xyz myfolder % python3 anderson_darling.py "[1,3,5,6,4,6,7,1,2,7]" "[1,3,5,6,4,6,7,1,2,7]"
The result, that appears on the Terminal is the following:
[1 3 5 6 4 6 7 1 2 7] % <-- array a
[1 3 5 6 4 6 7 1 2 7] % <-- array b
-1.4363560826434034 % <-- res.statistic
[0.325 1.226 1.961 2.718 3.752 4.592 6.546] % <-- res.critical_values
1.0 % <-- res.pvalue
My goal is make this Python file/function work on Matlab, and I type the following:
% Matlab arrays
a = [1,3,5,6,4,6,7,1,2,7];
b = [1,3,5,6,4,6,7,1,2,7];
% Convert MATLAB arrays to Python lists
py_a = py.list(a);
py_b = py.list(b);
% Call the python function "ADtest" within the "anderson_darling" function
py.anderson_darling.ADtest(py_a,py_b)
However, I get the following error on the Matlab Command Window:
Error using anderson_darling>ADtest
Python Error: NameError: name 'np' is not defined
How can I import “numpy” and “scipy” into the Matlab system?
Please consider that I have installed Anaconda, and my installed versions of Python, COnda and Matlab are the following ones.
From terminal:
% python3 --version
Python 3.12.4
% where python3
/opt/anaconda3/bin/python3
/usr/local/bin/python3
/usr/bin/python3
% conda --version
conda 24.7.1
% conda info --envs
# conda environments:
#
base * /opt/anaconda3
/usr/local/anaconda3
From the Matlab’s Command Window:
% Python Version for your system (inside Matlab)
% https://ch.mathworks.com/help/matlab/ref/pyenv.html
>> pyenv
ans =
PythonEnvironment with properties:
Version: "3.9"
Executable: "/Library/Developer/CommandLineTools/usr/bin/python3"
Library: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/libpython3.9.dylib"
Home: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9"
Status: Loaded
ExecutionMode: InProcess
ProcessID: "4128"
ProcessName: "MATLAB"
% Matlab version
>> version
ans =
'23.2.0.2515942 (R2023b) Update 7'
import numpy and scipy to matlab
BostonPlummer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.