user_1_1_1
user_1_1_1

Reputation: 923

Fast access to a MATLAB array of structs based on its id

I have a Matlab struct:

a(1).x=54.23; a(1).y=2.3; a(1).col=32.221; a(1).id=1;
a(2).x=5.23; a(2).y=3.3; a(2).col=2.221; a(2).id=2;

... and so on. Now i want to access the struct in a having id 73. I can think of doing a for loop but the thing is i have to access elements of array a several times like this based on id. Wat is the fastest data structure available for this purpose? Python like dictionary may work but i am not sure ow to implement it. Pointing out some code examples would be very helpful.

Upvotes: 0

Views: 52

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60780

Try this:

id=[a.id];
a(id==73)

It's not as efficient as a dictionary, but if it's fast enough for your purposes it's not worth looking further.

The a.id part evaluates to a comma-separated list of id values, which are concatenated in an array that you can then use for lookup.

Upvotes: 1

Related Questions