Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deal array values to a single field of a structure array (in Matlab)

I thought deal should do it but it does not, and I cannot find another nice solution.

I have an array a = 1:2. I would like to put the values 1 and 2 into a structure array b like so:

b(1).a = 1
b(2).a = 2

To my surprise, [b(1:2).a] = deal(1:2) does not deal the values, but puts the vector [1 2] into each field a of structure b:

>> b(1)
ans = 
    a: [1 2]

>> b(2)
ans = 
    a: [1 2]

Am I missing something with syntax here?

like image 444
texnic Avatar asked Oct 21 '22 08:10

texnic


1 Answers

deal does what it is expected to do. It distributes the input arguments among the outputs, and if it has only one argument (the vector 1:2) it replicates it as many times as the number of output arguments. You were probably looking for:

[b(1:2).a] = deal(1, 2); %// or simply [b.a] = deal(1, 2)

In the general case, you'll probably have to create a cell array from your values (e.g using num2cell) and use a comma-separated list, for instance:

C = num2cell(v);         %// v stores the values
[b.a] = deal(C{:});
like image 90
Eitan T Avatar answered Oct 27 '22 09:10

Eitan T