Search code examples
matlabfindlogiccell

How to choose between two values using 'or' in matlab?


I have the following code :

a = cell(4,1);
a{1} = [5 3 0 0];
a{2} = [0 3 5 0];
a{3} = [1 3 0 0];
a{4} = [0 3 2 0];

arrayind = 2;

b = a(cellfun(@(x)x(arrayind) == 1,a));
b{:}

How can I achieve this when an IF statement is used :

if r>2
b = a(cellfun(@(x)x(arrayind) == (1 | 2 | 3),a));
end

Basically saying, find 1, if not there then 2, if not there then 3...


Solution

  • ismember could perhaps be what you are looking for. Replacing the equality operator with ismember as follows:

    a = cell(4,1);
    a{1} = [5 3 0 0];
    a{2} = [0 3 5 0];
    a{3} = [1 3 0 0];
    a{4} = [0 3 2 0];
    arrayind = 1;
    b = a(cellfun(@(x) ismember(x(arrayind), [1 5]), a));
    

    would yield b = a([1, 3])