Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a struct array to another struct array?

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?

like image 396
Massoud Avatar asked Feb 28 '13 10:02

Massoud


2 Answers

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
like image 159
Dan Avatar answered Oct 11 '22 16:10

Dan


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.

like image 32
Shai Avatar answered Oct 11 '22 16:10

Shai