Joe C
Joe C

Reputation: 2827

Can we create a struct of array fields directly?

In MATLAB, if we do

 struct('a',1:4) 

it creates an array of struct... What I wanted is

 s = struct('a',[]);
 s.a = 1:4;

Can we do so in a single command?

Upvotes: 1

Views: 66

Answers (1)

lhcgeneva
lhcgeneva

Reputation: 1981

If you do

s.a = 1:4; 

Matlab creates a structure automatically, no need for the first line.

To get a performance difference between the two versions and also erfan's version (see comment under question) use timeit:

t1 = timeit(@no_preallocation);
t2 = timeit(@no_preallocation2);
t3 = timeit(@preallocation);

function no_preallocation()
    s.a = 1:4;
end

function no_preallocation2()
    s=struct('a',1:4);
end

function preallocation()
    s = struct('a',[]);
    s.a = 1:4;
end

I get

t1 = 1.3965e-06
t2 = 7.1217e-06
t3 = 7.1223e-06

which shows that allocating directly is substantially faster.

However, be aware that NOT preallocating can lead to weird behaviour, particularly in scripts, because you are not actually deleting the structure s before you are assigning the field a, meaning that if you had s in memory before the assignment, you will keep it and simply overwrite a, which might not be the intended behaviour. So preallocation as suggested by Edric and erfan seems to be best.

Upvotes: 2

Related Questions