MATLAB: Translate MATLAB Switch/Case Statements to if/elif statements in Python

if/elifloopspythonswitch casetranslate

Hello,
I am trying to translate some code from MATLAB to Python. This particular code is puzzling me as Python does not have or use Switch/Case statements. Reading that "the switch block tests each case until one of the case expressions is true" which reminds me of a while loop.
However, I am fairly certain that is not the case. Can somebody help me translate this and explain the conceptual differences between the if/elif statements and the switch/case statements?
Here is the code:
if (rem(length(varargin),2)==1)
error('Optional parameters should always go by pairs');
else
for i=1:2:(length(varargin)-1)
switch upper(varargin{i})
case 'MM_ITERS'
MMiters = varargin{i+1};
case 'SPHERIZE'
spherize = varargin{i+1};
case 'MU'
mu = varargin{i+1};
case 'LAMBDA'
lambda = varargin{i+1};
case 'TOLF'
tol_f = varargin{i+1};
case 'M0'
M = varargin{i+1};
case 'VERBOSE'
verbose = varargin{i+1};
otherwise
% Hmmm, something wrong with the parameter string
error(['Unrecognized option: ''' varargin{i} '''']);
end;
end;
end

Best Answer

if v[i] == 'MM_ITERS'
MMiters = v[i+1];
elif v[i] == 'SPHERIZE'
spherize = v[i+1];
...
else
... create an error here ...
There are other ways of programming this in python, just as there are in MATLAB. You could consider using a python set or python dictionary https://docs.python.org/2/library/stdtypes.html#set
For example, you could create a dict of names and default values. Then as you went through v, you could
if v[i] in d
d[v[i]] = v[i+1];
else
... create an error here
Related Question