How to transfer an array of structures to another array of structures?

I am trying to pass an array of structures 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

Unable to change the field n.

Did I miss something?

+5
source share
4 answers

You can assign each field of an array of structures directly to an array of cells, and then you can use dealto convert the structure to an array of cells:

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 about this

Edit: Or as Shai indicates that you can just go

[q.f] = s.f
+2
source

What about arrayfun

q = arrayfun( @(x,y) setfield( x, 'f', y.f ), q, s );

Apparently setfieldit intended only to install a single structure member in struct array - so arrayfun.

EDIT:
Dan.

+2

I wanted to make this sentence of Shai more visible, because it is easier to read.

[q.f] = s.f

+1
source

Although I would say @Dan answer is pretty canon for this question, I would like to introduce an alternative:

s(1).f = (1:3);
s(2).f = (4:6);
s(3).f = (7:9);

[q(1:length(s)).f] = s.f;

Although it is a bit more verbose than the syntax [q.f] = s.f, it does have the advantage of functioning as expected, even if qit was not pre-assigned to the correct size to be a copy s.

For instance:

s(1).f = (1:3);
s(2).f = (4:6);
s(3).f = (7:9);

[q.f] = s.f;

Returns q.fas 1x1 struct, equals(1).f

+1
source

All Articles