How to write a matlab function in Python?

8 Ansichten (letzte 30 Tage)
Harry Smith
Harry Smith am 12 Dez. 2022
Beantwortet: Al Danial am 15 Dez. 2022
I'm trying to transform a for loop from Matlab into python. I would like to create arrays of zeros and fill them via a for loop. In Matlab everything works perfectly, but in Python I have some problems The cycle is as follows:
cell=30
min=456544
max=566549
step=20
D=[1550,1500]
row_D=size(D,1)
column_D=size(D,2)
Nrs=size((1:step:row_D),2)
Ncs=size((1:step:column_D),2)
A = zeros(3,Nrs,Ncs);
B = zeros(3,3,Nrs,Ncs);
C = zeros(3,3,Nrs,Ncs);
D = zeros(12,Nrs,Ncs);
pos=zeros(3,1)
jj=0
for j=1:step:column_D
jj=jj+1
pos(1)=min+cell*(j-1)
ii=0
for i=1:step:row_D
ii=ii+1
pos(2)=max-cell*(i-1)
pos(3)=D(i,j)
[a b c d]= my_function(pos)
A(:,ii,jj)=a
B(:,:,ii,jj)=b
end
end
This is my convertion in Python:
import numpy as np
row_D=D.shape[0]
column_D=D.shape[1]
Nrs=int(row_D/step)
Ncs=int(column_D/step)
A=np.zeros((3,Nr,Nc))
B=np.zeros((3,3,Nr,Nc))
C=np.zeros((3,3,Nr,Nc))
D =np.zeros((12,Nr,Nc))
pos=np.zeros((3,1))
jj=0
for j in range(0,column_D,step):
jj=jj+1
pos[0]=min+cell*(j-1)
ii=0
for i in range(0,row_D,step):
ii=ii+1
pos[1]=max-cellsize*(i-1)
pos[2]=D[i,j]
%write the function here
Up to here everything works, but I can't write the function and fill my arrays A e B like on Matlab. Could anyone help me?

Antworten (1)

Al Danial
Al Danial am 15 Dez. 2022
You didn't show what my_function() looks like. Aside from that, the notation for populating A and B in NumPy is the same as in matlab, except you need to use brackets instead of parentheses:
A[:,ii,jj]=a
B[:,:,ii,jj]=b

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by