MATLAB Array of structure assignment

I have an array of structures. Let's say    s(1).value..., s(5).value. I have a vector of values, say vals = [1 2 3 4 5], which I want to assign to an array of structures. Therefore, written in pseudo-code, I want to: s(:).value = vals.

As shown below, there is a known solution. But is it really impossible to fulfill this assignment in 1 line, as in pseudocode?

% Vector of values
vals = [1 2 3 4 5];
n = length(vals);

% Initialize struct
s(n).values = 0;

% Put vals into my struct.values
[s(1:n).values] = ???

% Known solution that i am not satisfied with:
vals_c = num2cell(vals);
[s(1:n).values] = vals_c{:};

Best regards, Jonas

+4
source share
2 answers

Recently, having gone through the same phase, I thought I would answer this question.

To create a new single-field structure:

field = 'f';
value = {'some text';
         [10, 20, 30];
         magic(5)};
s = struct(field,value)

Create a non-scalar structure with several fields:

field1 = 'f1';  value1 = zeros(1,10);
field2 = 'f2';  value2 = {'a', 'b'};
field3 = 'f3';  value3 = {pi, pi.^2};
field4 = 'f4';  value4 = {'fourth'};

s = struct(field1,value1,field2,value2,field3,value3,field4,value4)

, , , . https://in.mathworks.com/help/matlab/ref/struct.html

+1

, cell2struct num2cell.

% Vector of values
vals = [1 2 3 4 5];
n = length(vals);


% Put vals into my struct.values
s = cell2struct(num2cell(vals), 'values', 1)

% transpose if orientation is important
s  = s.'; 

, . cell2struct , .

, , , .

+1

Source: https://habr.com/ru/post/1654342/


All Articles