user3185970
user3185970

Reputation: 69

Finding indexes of strings in a string array in Matlab

I have two string arrays and I want to find where each string from the first array is in the second array, so i tried this:

for i  = 1:length(array1);
    cmp(i) = strfind(array2,array1(i,:));
end

This doesn't seem to work and I get an error: "must be one row".

Upvotes: 0

Views: 211

Answers (2)

AlessioX
AlessioX

Reputation: 3177

Just for the sake of completeness, an array of strings is nothing but a char matrix. This can be quite restrictive because all of your strings must have the same number of elements. And that's what @neerad29 solution is all about.

However, instead of an array of strings you might want to consider a cell array of strings, in which every string can be arbitrarily long. I will report the very same @neerad29 solution, but with cell arrays. The code will also look a little bit smarter:

a = {'abcd'; 'efgh'; 'ijkl'};
b = {'efgh'; 'abcd'; 'ijkl'};

pos=[];
for i=1:size(a,1)
    AreStringFound=cellfun(@(x) strcmp(x,a(i,:)),b);
    pos=[pos find(AreStringFound)];
end

But some additional words might be needed:

  • pos will contain the indices, 2 1 3 in our case, just like @neerad29 's solution
  • cellfun() is a function which applies a given function, the strcmp() in our case, to every cell of a given cell array. x will be the generic cell from array b which will be compared with a(i,:)
  • the cellfun() returns a boolean array (AreStringFound) with true in position j if a(i,:) is found in the j-th cell of b and the find() will indeed return the value of j, our proper index. This code is more robust and works also if a given string is found in more than one position in b.

Upvotes: 1

neerad29
neerad29

Reputation: 473

strfind won't work, because it is used to find a string within another string, not within an array of strings. So, how about this:

a = ['abcd'; 'efgh'; 'ijkl'];
b = ['efgh'; 'abcd'; 'ijkl'];

cmp = zeros(1, size(a, 1));

for i = 1:size(a, 1)
    for j = 1:size(b, 1)
        if strcmp(a(i, :), b(j, :))
            cmp(i) = j;
            break;
        end
    end
end

cmp =

     2     1     3

Upvotes: 0

Related Questions