compare parts of strings

조회 수: 86 (최근 30일)
ludvikjahn
ludvikjahn 2015년 3월 3일
편집: Stephen23 2015년 3월 4일
good morning, I want to know if there is a way to compare parts of strings in matlab.
For example: I want to find a string with 'dog':
A=['dog','cat','ball','hot-dog','god','dogged']
compared to
B=['dog']
should return:
[1,0,0,1,0,1]
In the same way, if I want to compare:
A=['red','green','yellow'] with
B=['greener', 'baseball', 'reddish'],
that should return either [1,1,0] or [1,0,1].
Just want to know if it is possible, because it seems quite impossible for my MATLAB skills.
Thanks

채택된 답변

Stephen23
Stephen23 2015년 3월 3일
편집: Stephen23 2015년 3월 4일
In MATLAB the square brackets are not a list operator (as a lot of beginners think), but actually a concatenation operator , so your code:
['dog','cat','ball','hot-dog','god','dogged']
simply concatenates all of those strings to give
'dogcatballhot-doggoddogged'
which is probably not what you wanted. And
['dog']
does nothing at all, because there is nothing to concatenate.
Instead you need to use a cell array to store the strings, like this:
>> A = {'dog','cat','ball','hot-dog','god','dogged'};
and 'dog' can simply be defined as a simple string like this
>> B = 'dog';
Then you can find the start indices of any match using strfind:
>> strfind(A,B)
ans =
[1] [] [] [5] [] [1]
which tell us the indices of where string B is found in each of the string in A. If you only need to know if the string exists in A then you can use cellfun on its output:
>> ~cellfun('isempty',strfind(A,B))
ans =
1 0 0 1 0 1
Likewise we can compare a cell array to see if there are any strings contained in the the strings of another cell array, although this is a little more code:
>> A = {'greener', 'baseball', 'reddish', 'mellow-yellow', 'greenspan'};
>> B = {'red', 'green', 'yellow'};
>> C = cellfun(@(s)strfind(A,s),B,'UniformOutput',false);
>> any(~cellfun('isempty',vertcat(C{:})),1)
ans =
1 0 1 1 1
You might also be interested in the matrix, which shows which substrings match between the two cell arrays (the rows=B, the columns=A):
>> ~cellfun('isempty',vertcat(C{:}))
ans =
0 0 1 0 0
1 0 0 0 1
0 0 0 1 0
Note that in all of these examples the code checks if the string/s in B exist in A.
  댓글 수: 1
ludvikjahn
ludvikjahn 2015년 3월 3일
wow! that's very easy!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by