MATLAB: How to add a new field to a struct array inside a cell array

anonymous functionsarrayfuncellfunfunction handleMATLABstructstructfun

Hi all 🙂
I'm trying to add a new field to every structure contained withing a cell array myTLS {1×300}, using anonymous Functions, that is,with cellfun / arrayfun.
The structure it self has the same Fields / Fieldnames in every cell. Only the content is different.
It looks something like this, for example for the 2 first cell elements.
A{1, 1}.f1trajectory = 1:10
A{1, 1}.f2TLSid = 7
A{1, 1}.f3FZklasse = "2.PkwA"
A{1, 2}.f1trajectory = 2:11
A{1, 2}.f2TLSid = 3
A{1, 2}.f3FZklasse = "3.LkwA"
Now I have another cell array: BnewCell: {1×300}, and inside each a double [1×1]. The value of each cell corresponds to each vehicle from myTLS {1×300}.
How could I add a new 4th. field ‘f4Orient’ for all the structures, that is, for the structure inside every of the 300 Cell elements? Preferably using anonymous function, that is, cellfun or arrayfun.
It should look like something like this:
BnewCell = {5 ,12,17,19} % Orientation values
A{1, 1}.f4Orient = BnewCell{1,1}
A{1, 2}.f4Orient = BnewCell{1,2}
I’m having trouble formulating an Anonymous Function, which I could use together with cellfun or arrayfun, to accomplish this inside my cell array myTLS.
af1x = @(x) x % get contents of BnewCell
C = cellfun (af1x,BnewCell,'UniformOutput',false)
I though about something like this, but it doesn't work when using twice “=“
afx2 = @(x) x(:).f4Orient = @af1x(x); % get error, cant use twice "="
I’d greatly appreciate your help.
Thanks in advance

Best Answer

afx2 = cellfun(@(S,K) setfield(S, 'f4Orient', K), A, BnewCell);