Alex
Alex

Reputation: 77

MATLAB: Run multiple cases in switch

Is there a method for running multiple case statements (say 2 out of 3) in a MATLAB switch? Or do I have to use a series of if statements? I would like do something similar to:

test = {'test1','test2'}
switch test
    case 'test1'
        disp('test1')
    case 'test2'
        disp('test2')
    case 'test3'
        disp('test3')
end

Output:

test1
test2

On a side note: is there any way to parallelize such code so that the different cases can be run simultaneously?

Upvotes: 0

Views: 1829

Answers (2)

OmG
OmG

Reputation: 18838

A solution can be put the switch into a function and then use the cellfun. Hence, define the function:

function a = func(test)
    switch test
        case 'test1'
            disp('test1')
        case 'test2'
            disp('test2')
        case 'test3'
            disp('test3')
    end
end

then, apply to the test:

cellfun(@func, test)

The result would be:

test1 
test2

Upvotes: 2

Marouen
Marouen

Reputation: 945

the if statement would be more appropriate if you 1/ want to test for multiple cases 2/parallelize.

something like

if ismember('test1',test)
     %code
end

if you want to make it parallel, you can do it through the following:

test is your data, case is the cell containing all possiblities

parfor(i=1:length(cases)){ %you need to parse the cases not the data
      if(ismember(case{i},test)){
       %code
      }

}

Upvotes: 2

Related Questions