I am trying to pass a struct array to another without success.
s(1).f = (1:3);
s(2).f = (4:6);
s(3).f = (7:9);
q(1).n = 'nameA';
q(2).n = 'nameB';
q(3).n = 'nameC';
q(3).f = [];
q.f = s.f
The field n
shouldn't be modified.
Do I miss something?
You can assign each field of an array of structs directly to a cell array and then you can use deal
to convert a struct to a cell array:
s(1).f = (1:3);
s(2).f = (4:6);
s(3).f = (7:9);
q(1).n = 'nameA';
q(2).n = 'nameB';
q(3).n = 'nameC';
c = cell(3,1);
[c{:}] = deal(s.f);
[q.f] = c{:};
Here is a good article on this sort of thing
Edit: Or as Shai points out you can just go
[q.f] = s.f
How about arrayfun
q = arrayfun( @(x,y) setfield( x, 'f', y.f ), q, s );
Apparently setfield
is only for setting one struct element in struct array -- thus the arrayfun
.
EDIT:
a much better answer given by Dan.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With