Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - Indexing an array by using string values

Tags:

matlab

I have a predefined array of 20 position which correspond to 20 joint out of my body. The joints are marked with string values (e.g. 'left_knee', 'head', 'left_eye', etc.).

I want to refer to a certain value within the array by using the attached string value. For example I want to store the position of the observed joints. Initially all the position within the array are (-1 , -1) and then if I spot a certain joint I want to do something like Joints('left_knee') = [100 200].

How can I do this in Matlab?

like image 657
Simon Avatar asked Nov 08 '12 09:11

Simon


1 Answers

How about structs?

Joints.left_knee = [100 200];
Joints.head      = [-1 -100];

Get all fields with fieldnames, refer to individual entries dynamically like so:

someVar = 'left_eye';
Joints.(someVar) = [200 250];

etc. If you happen to have multiple joints, all needing the same sort of data but they all belong to the same system, you can make multi-D structs, too:

Joints(1).left_knee = [100 200];
Joints(1).head      = [-1 -100];

Joints(2).left_knee = [200 450];
Joints(2).head      = [-10 -189];

Joints(3).left_knee = [-118 264];
Joints(3).head      = [+33  78];

Just to show you some techniques useful in the context of multi-D structs:

>> someVar = 'head';
>> Joints.(someVar)     % will be expanded cell-array, 1 entry for each dimension
ans =
    -1  -100
ans =
   -10  -189
ans =
    33    78
>> [Joints.(someVar)]   % will collect those data in regular array
ans =
    -1  -100   -10  -189    33    78
>> {Joints.(someVar)}   % will collect those data in cell array
ans = 
    [1x2 double]    [1x2 double]    [1x2 double]
>> [A,B,C] = deal(Joints.(someVar));  % will assign data to 3 separate vars
A =
    -1  -100
B =
   -10  -189
C =
    33    78

Type help struct for more info and learn about relevant functions.

like image 147
Rody Oldenhuis Avatar answered Sep 27 '22 19:09

Rody Oldenhuis