How to write a matlab function in Python?

4 ビュー (過去 30 日間)
Harry Smith
Harry Smith 2022 年 12 月 12 日
回答済み: Al Danial 2022 年 12 月 15 日
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?

回答 (1 件)

Al Danial
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

カテゴリ

Help Center および File ExchangeCall Python from MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by