Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab vector to comma-separated list conversion in one line

Tags:

matlab

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.

like image 414
Reed Espinosa Avatar asked Dec 13 '16 19:12

Reed Espinosa


1 Answers

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

like image 162
Suever Avatar answered Oct 22 '22 18:10

Suever