Arthur Tarasov
Arthur Tarasov

Reputation: 3791

Can I make a struct start with n-th field in Matlab?

Whenever I create a structure, it starts from field 1 by default. I am working with a data file where I have to loop through a part of it to get data to create the structure. In this small example, I loop only through 3 to 5, skipping 1 and 2.

for i = 3:5
    a(i).b = 1;
end

The result is a structure with empty 1 and 2 fields:

   b
1  []
2  []
3  1
4  1
5  1

Is there a way to start a struct with n-th field so it looks like this:

   b
3  1
4  1
5  1

The reason I want to do this is because in my real structure I get about 100 empty fields before 10 fields with the data and it doesn't look very neat.

Upvotes: 0

Views: 77

Answers (1)

sco1
sco1

Reputation: 12214

To answer the explicit question, there is no way to do this with a MATLAB structure. You could use a map container to store your data.

For example:

keys =  [3, 4, 5, 6];
values = [1, 1, 1, 1];
a = containers.Map(keys, values);

And you can access your data using a(3), a(6), etc.

That said, the memory overhead for empty structures is minimal, the difference between initializing your array with for ii = 3:5 and for ii = 1:3 is 16 bytes.

Upvotes: 4

Related Questions