MATLAB: How to use cellfun with a structure?

Imagine an array of cells that consists of identical structures (in terms of layout), as an example cellArraybelow. How can I apply cellfunthese structures to a specific field?

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

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

out = cellfun(@plus, cellArray?????, {50, 50}, 'UniformOutput', false);
+4
source share
1 answer

You can write a custom function add_val2(x, y)that adds yto the field x.val2and calls cellfun()with @add_val2instead @plus.

First create a function add_val2.m:

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

Then the challenge cellfun()is simple as

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

that leads to

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

>> out{2}
ans = 
  struct with fields:
    val1: 1000
    val2: 2050
+5
source

Source: https://habr.com/ru/post/1692876/


All Articles