jeudi 26 juillet 2018

Switch/Case in Matlab to If/Else Python

I am working on translating some code from Matlab into Python. Currently I am working on this:

switch SIGNATURES_TYPE
    case 1
        rand('seed',5);
        load('USGS_1995_Library')
        wavlen=datalib(:,1);    % Wavelengths in microns
        [L n_materiais]=size(datalib);
        # select randomly
        sel_mat = 4+randperm(n_materiais-4);
        sel_mat = sel_mat(1:p);
        M = datalib(:,sel_mat);
        # print selected endmembers
        clear datalib wavelen names aux st;
    case 2
        error('type not available')
    case 3
        M = rand(L,p);
    case 4
        M = randn(L,p);
    case 5
        L=p;
        M = diag(linspace(1,(1/(COND_NUMBER)^(1/DECAY)),p).^DECAY);
    case 6
        L=p;
        M = diag(linspace(1,(1/(COND_NUMBER)^(1/DECAY)),p).^DECAY);
        A = randn(p);
        [U,D,V] = svd(A);
        M = U*M*V';
        clear A U D V;
    otherwise
        error('wrong signatute type')
end

Previously I had worked on a similar Switch/Case code:

for i=1:2:(length(varargin)-1)
    switch upper(varargin{i})
        case 'MM_ITERS'
            MMiters = varargin{i+1};
        case 'SPHERIZE'
            spherize = varargin{i+1};

The latter I was able to translate to this:

for i in range(1, 2, length(*args)-1):
        if (arg[i].upper() == "MM_ITERS"):
            MMiters = arg(i+1)
        elif (arg[i].upper() == "SPHERIZE"):
            spherize = arg(i+1)

However for the former I am wondering how I can create similar if statements. For example, for the first case can my code be something like:

if SIGNATURES_TYPE == 0:
    ** finish function

I wanted to know if something like this works or if it would be better to perhaps separate out statements into separate functions and then call them?

Thanks for the help and input!

Aucun commentaire:

Enregistrer un commentaire