0

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".

2
  • Do the two arrays have the same strings, but at different locations? Commented Feb 25, 2016 at 20:37
  • strfind is used to find a string within another string, not within an arrays of strings. Commented Feb 25, 2016 at 20:45

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.