5

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?

0

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

11 Comments

while you are at it, why not just [q.f] = s.f?
Thank you all for your help! Shai´s edit works great. But your suggestion with dealcommand doesn´t work. The error message is: "The left hand side has c{:} inside brackets, which requires that c be defined, so that the number of expected results can be computed"
@Massoud what's wrong with '[q.f]=s.f;' '[q.fNew]=s.fNew;'? If this is a new question - post it as such.
Thank you, yes I agree now! The same counts for s.f, which also delivers a comma separated list (CSL). The [] on lhs in combination with a CSL on the rhs is the replacement syntax for deal()command since Matlab version 7.
@Dan @Shai Worth noting the [q.f] = s.f notation only works if q is preallocated to the correct size. If q has not been previously defined, this approach will only define q as s(1).f
|
2

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.

2 Comments

Can you apply this without knowing the name of 'f' and multiple fields like 'f'? So add all fields from s to q?
@Leo you can apply the method from Dan's answer only loop on all fields using fieldnames.
1

I wanted to make this suggestion by Shai more visible because it’s easier to read.

[q.f] = s.f

Comments

1

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 [q.f] = s.f 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 q.f as a 1x1 struct equal to s(1).f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.