登录论坛

查看完整版本 : converting between matlab and python [on hold]


poster
2019-11-24, 06:07
<p>I am new in python. pleae tell me How I can convert this matlab file to python, </p>

<pre><code>classdef TGrid < handle

properties
% properties common for all grids
NzEarth % number of Earth layers
Nza % number of air layers
end

methods

%set airLayers for the grid
function obj = setAirLayers(obj,varargin)

Method = 'fixed height'; % OPTIONS: mirror, Fixed Height, Read From File
MaxHeight = 10^6 ; % Fixed height of top
nzAir = 15 ; % number of layers
InputFile = [];

n = length(varargin);
if mod(n,2)
error('Arguments must occur in pairs')
end
for k = 1:2:n
option = lower(varargin{k});
switch option
case 'method'
Method = lower(varargin{k+1});
nzAir = 10;
case 'maxheight'
MaxHeight = varargin{k+1};
case 'nlayers'
nzAir = varargin{k+1};
case 'inputfile'
InputFile = varargin{k+1};
end
end

switch Method
case 'mirror'

dzAir = obj.Dz(obj.Nza+1:obj.Nza+nzAir).*(3.^(0:nzAir-1))';

case 'fixed height'
z1_log = log10(obj.Dz(1));
dlogz = (log10(MaxHeight)-z1_log)/(nzAir);
z = 10.^(z1_log:dlogz:log10(MaxHeight));
dzAir = diff(z);
case 'read from file'
fid = fopen(InputFile);
[dzAir,nzAir] = fscanf(fid,'%f','inf');
end
[n,~] = size(dzAir);
if n == 1
dzAir = dzAir.';
end
obj.Nza = nzAir;
obj.Dz = [dzAir(end:-1:1) ; obj.Dz];
obj.Nz = length(obj.Dz);
obj.dualLengths;
obj.setIndices;
end % setAirLayers


end % methods
end % classdef
</code></pre>

<p>I defined in python in this way:</p>

<p>import numpy as np</p>

<p>class TGrid:
def <strong>init</strong>(self, NzEarth, Nza):
self.NzEarth = NzEarth # number of Earth layers
self.Nza = Nza # number of Earth layers</p>

<p>def setAirLayers(obj=None,varargin=None,*args,**kwargs):</p>

<pre><code>Method='fixed height'
MaxHeight=10 ** 6
nzAir=15
InputFile=[]
n=len(varargin)
if n % 2 == 0:
print('Arguments must occur in pairs')

for k in range(1,n,2).reshape(-1):
option=varargin[k].lower()
if 'method' == option:
Method=varargin[k + 1].lower()
nzAir=10
if 'maxheight' == option:
MaxHeight=varargin[k + 1]
if 'nlayers' == option:
nzAir=varargin[k + 1]
if 'inputfile' == option:
InputFile=varargin[k + 1]
if 'mirror' == Method:
dzAir=multiply(obj.Dz(arange(obj.Nza + 1,obj.Nza + nzAir)),(3.0 ** (arange(0,nzAir - 1))).T)
elif 'fixed height' == Method:
z1_log=np.log10(obj.Dz(1))
dlogz=(np.log10(MaxHeight) - z1_log) / (nzAir)
z=10.0 ** (range(z1_log,np.log10(MaxHeight),dlogz))
dzAir = diff(z)
if 'read from file' == Method :
fid = open (InputFile, 'r')
n,__=np.size(dzAir,nargout=2)
if n == 1:
dzAir=dzAir.T
obj.Nza = nzAir
obj.Dz = [[dzAir((end,1,- 1))],[obj.Dz]]
obj.Nz = len(obj.Dz)
obj.dualLengths
obj.setIndices
return obj
</code></pre>

<p>if <strong>name</strong> == '<strong>main</strong>':
pass</p>



More... (https://stackoverflow.com/questions/59003150/converting-between-matlab-and-python)