How to write a matlab function in Python?
3 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
Al Danial
2022-12-15
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!