How to write a matlab function in Python?
조회 수: 2 (최근 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!