4

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);
1
  • Do the docs mention this particular case? Commented Jan 29, 2018 at 14:12

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.