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
我想让Shai的建议更加明显,因为它更容易阅读。
[qf] = sf
Though I'd say @Dan's answer is pretty canon for this question, I'd like to present an alternative:
s(1).f = (1:3);
s(2).f = (4:6);
s(3).f = (7:9);
[q(1:length(s)).f] = s.f;
Though slightly more verbose than the [qf] = sf
syntax, it has the advantage of functioning as expected even if q
has not been preallocated to the correct size to be a copy of s
.
For example:
s(1).f = (1:3);
s(2).f = (4:6);
s(3).f = (7:9);
[q.f] = s.f;
Returns qf
as a 1x1 struct
equal to s(1).f
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.