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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With