Using loops and strcmp. Have 1 master char array, need to find matches of each entry in 2 other arrays.

1 次查看(过去 30 天)
I have 3 variables, each are list-like char arrays.
Var1 is a list of unique 3-letter strings, in alphabetical order.
Var2 and Var 3 are lists where the entries are a random combination of the unique strings in Var1. The unique strings can appear multiple times or not at all. Var 2 and 3 are of equal length, but not Var1.
What I have so far:
num_of_matches1=0;
num_of_matches2=0;
for k=1:length(charstring1)
for i=1:length(charstring2)
MatchChecker=strcmp(charstring1(k),
charstring2(i));
if MatchChecker==1
num_of_matches1=num_of_matches1+1;
end
end
for j=1:length(charstring3)
MatchChecker=strcmp(charstring1(k),
charstring3(j));
if MatchChecker==1
num_of_matches2=num_of_matches2+1;
end
end
Eventually, I need to print results in a table like this:
Charstring Name Matches in Var2 Matches in Var3
ABC 5 8
BAS 8 7
etc.

采纳的回答

dpb
dpb 2014-3-28
编辑:dpb 2014-3-29
Oh, that's pretty simple, then...
>> for i=1:size(Var1,1)
disp([sum(ismember(Var2,Var1(i,:),'rows')) ...
sum(ismember(Var3,Var1(i,:),'rows'))])
end
2 4
1 2
4 1
>>
You can go further and replace the loop construct if desired...
ADDENDUM:
Altho in that case entails converting VarN to cellstring arrays owing to addressing a character string by the second address isn't supported in arrayfun syntax.
>> (cellfun(@(x) sum(ismember(cellstr(Var2),x)),cellstr(Var1)))
ans =
2
1
4
>>
  2 个评论
Alexander
Alexander 2014-3-29
One more thing; I need to save the results of the for loop as an array. Also in the array, the third column is the sum of col 1 and 2. What you gave gives me displays the results, but I need them as an array that I can call later on.
dpb
dpb 2014-3-30
编辑:dpb 2014-3-30
A) What does the result of the note in the ADDENDUM return? :)
B) You can't write a sum of two terms? Gotsa' leave something for the "exercise for the student" :)
C) If you still want to stay with the looping solution, preallocate a results array and populate it with the answers as you iterate thru the Var1 variable.

请先登录,再进行评论。

更多回答(1 个)

dpb
dpb 2014-3-30
编辑:dpb 2014-3-31
>> mtch=[cellfun(@(x) sum(ismember(C2,x)),C1) ...
cellfun(@(x) sum(ismember(C3,x)),C1)];
>> mtch=[mtch sum(mtch,2)]
mtch =
2 4 6
1 2 3
4 1 5
>>
NB:
I converted to cellstr before for brevity...
C1 = cellstr(Var1); % etc., ...

类别

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