Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab array of struct : Fast assignment

Is there any way to "vector" assign an array of struct.

Currently I can

edges(1000000) = struct('weight',1.0); //This really does not assign the value, I checked on 2009A.
for i=1:1000000; edges(i).weight=1.0; end; 

But that is slow, I want to do something more like

edges(:).weight=[rand(1000000,1)]; //with or without the square brackets. 

Any ideas/suggestions to vectorize this assignment, so that it will be faster.

Thanks in advance.

like image 748
sumodds Avatar asked Oct 28 '11 06:10

sumodds


2 Answers

This is much faster than deal or a loop (at least on my system):

N=10000;
edge(N) = struct('weight',1.0); % initialize the array
values = rand(1,N);  % set the values as a vector

W = mat2cell(values, 1,ones(1,N)); % convert values to a cell
[edge(:).weight] = W{:};

Using curly braces on the right gives a comma separated value list of all the values in W (i.e. N outputs) and using square braces on the right assigns those N outputs to the N values in edge(:).weight.

like image 157
Alistair Avatar answered Nov 15 '22 11:11

Alistair


You can try using the Matlab function deal, but I found it requires to tweak the input a little (using this question: In Matlab, for a multiple input function, how to use a single input as multiple inputs?), maybe there is something simpler.

n=100000;
edges(n)=struct('weight',1.0);
m=mat2cell(rand(n,1),ones(n,1),1);
[edges(:).weight]=deal(m{:});

Also I found that this is not nearly as fast as the for loop on my computer (~0.35s for deal versus ~0.05s for the loop) presumably because of the call to mat2cell. The difference in speed is reduced if you use this more than once but it stays in favor of the for loop.

like image 26
Aabaz Avatar answered Nov 15 '22 11:11

Aabaz