MATLAB to Python

In case I need to convert MatLab code to Python again…

origunits(1:3)
->    
origunits[:3]
## Because MatLab starts with 1 and includes the last number
## and Python does neither
fgetl(fid)  
->    
fid.readline().rstrip()
strcmp(unt(1:3),'ori')
->    
unt[:3] == 'ori'
error('Unknown units')
->    
raise Exception('Unknown units')
switch unt(1:3),
    case 'fee',
       ...
    case 'met',
       ...
->    
if unt[:3] == 'fee':
    ...
elif unt[:3] == 'met':
    ...
## Python does not have a 'switch-case' control
fprintf('Station: %s\n',pred.station);
->    
print( 'Station: {0}'.format(pred.station) )
## Newline char not needed
clear pred
->    
del pred
xtide=struct('name',repmat(' ',ncon,8),'speed',zeros(ncon,1),...
             'startyear',0,'equilibarg',zeros(ncon,68),...
             'nodefactor',zeros(ncon,68));
->
xtide = dict({'name':numpy.tile(' ',(ncon,8)), 
              'speed':zeros((ncon,1)),
    	      'startyear':0,
              'equilibarg':zeros((ncon,68)),
              'nodefactor':zeros((ncon,68)) })
## Numpy.tile replaces 'repmat'. Add parenthesis for 'zeros'.

Leave a comment