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.
  댓글 수: 2
dpb
dpb 2014년 3월 28일
How about a mini-dataset to play with that illustrates characteristic data?
Alexander
Alexander 2014년 3월 28일
Below are variables.
Var1=[ABC; XYZ; ZZZ]
Var2=[XYZ; ZZZ; ZZZ; ZZZ; ABC; ABC; ZZZ]
Var3=[ABC; ZZZ; ABC; ABC; XYZ; XYZ;ABC]
Need output
Name Match in Var2 Match in Var3
ABC 2 4
XYZ 1 2
ZZZ 4 1

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

채택된 답변

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