简体   繁体   中英

get index for corresponding string matching a string within a vector

I have a vector of different string name;

A = {

    'alex'
    'alex'
    'sophie'
    'alex'
    'david'
    'sophie'
    'david'
    'david'
    'sophie'
    'alex' };

and for which correspond 2 variables, lets say age and size type_age = [1:10]; type_size = [10:10:100];

I want to get the be able to do something like

 un_a = unique(A);
 f = find(A==un_a(1)); % I know this would work if I had numbers and not string..

 alex_age = type_age(f);
 alex_size = type_size(f);

 plot(alex_age,alex_size,'.r',sophie_age,sophie_size,'.b');

While above is just an example, I would like to be able to generate something like that to make a scatter plot of my variables differently coloured for each name.

So where I am stuck is to get the index (f) for the corresponding unique name within my array of string.

On the other hand, if there is any easier way of doing that , please let me know. I in fact have a huge data set.

Also I don't know if strcmp can be handy there - or using a switch case.. ??

Thanks a lot in advance!

It is already done for you. Just use full syntax of the unique function:

[un_a,b,m] = unique(A);

now

un_a = 

'alex'
'david'
'sophie'


b =

10
 8
 9


m =

 1
 1
 3
 1
 2
 3
 2
 2
 3
 1

using m you can extract data from other related arrays like this:

>> alex_age = type_age( m==1 )
alex_age =

 1     2     4    10

>> david_age = type_age( m==2 )
david_age =

 5     7     8

>> sophie_age = type_age( m==3 )
sophie_age =

 3     6     9

None that the number in comparison operators is the index of the corresponding name in un_a array.

EDIT @sophie, in your context un_a = A(b) , so b holds position of the unique elements in the original array A . For example, you have four 'alex' (stored in un_a{1} ) in your array at positions 1,2,4,10, so you get b(1)=10 as index of one of them (last one, but I'm not sure this is documented, it may arise from the search algorithm). If you want to get other indices, you do like this:

alex_idx = find( m==m(b(1)) )
alex_idx =

 1
 2
 4
10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM