Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - How do I compare two strings letter by letter?

Essentially, I have two strings of equal length, let's say 'AGGTCT' and 'AGGCCT' for examples sake. I want to compare them position by position and get a readout of when they do not match. So here I would hope to get 1 out because there is only 1 position where they do not match at position 4. If anyone has ideas for the positional comparison code that would help me a lot to get started.

Thank you!!

like image 640
user2180513 Avatar asked Dec 16 '22 10:12

user2180513


2 Answers

Use the following syntax to get the number of dissimilar characters for strings of equal size:

sum( str1 ~= str2 )

If you want to be case insensitive, use:

sum( lower(str1) ~= lower(str2) )

The expression str1 ~= str2 performs char-by-char comparison of the two strings, yielding a logical vector of the same size as the strings, with true where they mismatch (using ~=) and false where they match. To get your result simply sum the number of true values (mismatches).

EDIT: if you want to count the number of matching chars you can:

  1. Use "equal to" == operator (instead of "not-equal to" ~= operator):

    sum( str1 == str2 )
    
  2. Subtract the number of mismatch, from the total number:

    numel(str1) - sum( str1 ~= str2 )
    
like image 113
Shai Avatar answered Dec 30 '22 00:12

Shai


You can compare all the element of the string:

r = all(seq1 == seq2)

This will compare char by char and return true if all the element in the resulting array are true. If the strings can have different sizes you may want to compare the sizes first. An alternative is

r = any(seq1 ~= seq2)

Another solution is to use strcmp:

r = strcmp(seq1, seq2)
like image 43
Cavaz Avatar answered Dec 29 '22 22:12

Cavaz