6

In Matlab I often want to assign multiple values from a numeric vector to a given field of a structure array.

b = 1:3;
x(1).a = b(1);
x(2).a = b(2);
x(3).a = b(3);

It seems like there should be a way to make this assignment in a single line but two lines is the best I can come up.

c = num2cell(b);
[x.a] = c{:};

Is there a way to convert a numeric vector into a comma-separated list? I'm looking for something like:

[x.a] = num2csl(b);

Note that I am assuming that length(x) == length(b) here.

2
  • 2
    I like Octave syntax [x.a] =num2cell(b){:}; Commented Dec 13, 2016 at 19:49
  • 1
    @rahnema1 I've always wanted that to work in Matlab. I had no idea that it actually worked in Octave. Thanks. Commented Dec 13, 2016 at 20:06

2 Answers 2

6

Yes, you can just use struct. If you provide a cell array as the value for a given fieldname, MATLAB will create a struct the same size as that field and use each element within the cell array to populate the corresponding struct in the resulting array.

x = struct('a', num2cell(b))

In general, there is no way to easily return a comma-separated list from a function

Sign up to request clarification or add additional context in comments.

2 Comments

My structure x frequently has other fields that I don't want to overwrite so I really need a comma-separated list but it sounds like the answer is that there is currently no reasonable way to do that. Thanks!
Often it's also important to remember that there is really no harm in having two lines, especially if they improve readability.
3

This can only be done with a function if x already exists and has the correct number of elements:

b = 1:3;

x = repmat(struct, size(b));
[x.a] = num2csl(b);

This works if num2csl.m makes use of the special output convention varargout as follows:

function varargout = num2csl(a)
varargout = num2cell(a);

If on the other hand, x does not already exist, then this one-liner will initialize it, as previously pointed out by Suever:

x = struct('a', num2cell(b));

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.