Using loops and strcmp. Have 1 master char array, need to find matches of each entry in 2 other arrays.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
dpb
am 28 Mär. 2014
Bearbeitet: dpb
am 29 Mär. 2014
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 Kommentare
dpb
am 30 Mär. 2014
Bearbeitet: dpb
am 30 Mär. 2014
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.
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!