matlabanonymous-functioncell-array

If-then-else in anonymous function


I'm trying to use some kind of if-then-else statement in an anonymous function, which itself is part of cellfun. I have a cell array that contains a number of double matrices. I would like to substitute all positive numbers in all double matrices with +1, and all negative numbers with -1. I am wondering if I can use an anonymous function rather than coding a separate function that I then call from within the cellfun?

Here's the toy example:

mat = [2, 2, 0, -2; -2, 0, 0, 2; -2, 2, -2, 2]
cellarray = repmat({mat}, 3, 1)

I'm looking for something like this:

new_cellarray = cellfun(@(x) if x > 0 then x = 1 elseif x < 0 then x = -1, cellarray, 'UniformOutput', false)

I also tried this, however, apparently I am not allowed to put an equal sign into an anonymous function.

new_cellarray = cellfun(@(x) x(x > 0) = 1, cellarray, 'UniformOutput', false)
new_cellarray = cellfun(@(x) x(x < 0) = -1, cellarray, 'UniformOutput', false)

Solution

  • You can use the built-in function sign, which returns 1, 0, or -1 depending on its input:

    mat = [2, 2, 0, -2; -2, 0, 0, 2; -2, 2, -2, 2];
    cellarray = repmat({mat}, 3, 1);
    new_cellarray = cellfun(@sign, cellarray, 'UniformOutput', false);