Search code examples
matlabstructcell-array

MATLAB: How to use cellfun with a struct?


Imagine a cell array that consists of identical structs (in terms of layout), as the example cellArray below. How can I apply cellfun to a specific field of these structs?

cellArray{1,1}.val1 = 10;
cellArray{1,1}.val2 = 20;
cellArray{1,2}.val1 = 1000;
cellArray{1,2}.val2 = 2000;

How to use cellfun in order to add the value 50 to all cells, but only to the field val2?

out = cellfun(@plus, cellArray?????, {50, 50}, 'UniformOutput', false);

Solution

  • You can write a custom function add_val2(x, y), which adds y to the field x.val2, and call cellfun() with @add_val2 instead of @plus.

    First, create the function add_val2.m:

    function x = add_val2(x, y)
        x.val2 = x.val2 + y;
    end
    

    Then, calling cellfun() is as simple as

    out = cellfun(@add_val2, cellArray, {50, 50}, 'UniformOutput', false);
    

    which results in

    >> out{1}
    ans = 
      struct with fields:
        val1: 10
        val2: 70
    
    >> out{2}
    ans = 
      struct with fields:
        val1: 1000
        val2: 2050