user3270686
user3270686

Reputation: 81

How to find two or more equal strings stored in two different vectors in matlab

I have two vectors (of different size) with strings in a data file. I want to find the locations of two (or more) similar strings in each of these vectors. E.g.:

a=['str1', 'str2', 'str3', 'str4', 'str5', 'str6'];
b=['str3', 'str1', 'str4', 'str4'];

I want an output like:

b(1) corresponds to a(3)
b(2) corresponds to a(1)
b(3) corresponds to a(4)
b(4) corresponds to a(4)

is it possible?

Upvotes: 0

Views: 40

Answers (2)

Geoff
Geoff

Reputation: 1603

An alternative is to use the ismember command which will return an array of logicals indicating whether the element of array b is a member of array a. It can also return a vector which indicates where in a the element of b is found. Using your example:

[ismem,idxa]=ismember(b,a)

returns the results

ismem =
 1     1     1     1
idxa =
 3     1     4     4

So we see that each member of b is in a (due to the ismem vector being all ones) and we see where in a is that element of b from the idxa vector. (Note that if b has an element that is not in a then there would be a zero element in both vectors.)

Upvotes: 2

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

If you store your strings in cell arrays, you can do it like this:

>> a = {'str1', 'str2', 'str3', 'str4', 'str5', 'str6'};
>> b = {'str3', 'str1', 'str4', 'str4'};
>> result = cellfun(@(x) find(strcmp(a, x)), b, 'UniformOutput', false);

result = 

    [3]    [1]    [4]    [4]

Note: result is a cell array. Therefore, result{i} == j means b(i) corresponds to a(j). If b(i) was not found in a, result{i} is empty.

Upvotes: 2

Related Questions