Compare two strings and count the same words

2 views (last 30 days)
Hi @ all,
I have two strings. The first one are measurement results which looks like this:
iwant="Gruppe 1; Gruppe 2; Gruppe 3; Gruppe 3; ; Gruppe 6"
The second string are an overview about all groups we could find. It looks like this:
Vergleichsstring_RL="Gruppe 1; Gruppe 2; Gruppe 3; Gruppe 4; Gruppe 5; Gruppe 6; Gruppe 7" ...
So in the end I want to compare these strings and count how many of each "Gruppe" were found. The difficulty is that not all points are called Gruppe. If there is now result for e.g. Gruppe 5, there should be a zero written.
I tried it like below. It doesn't work. I import several measurement files and it seems that in this step something goes wrong:
idx = strfind(iwant(:,2), Vergleichsstring_RL);
idx = find(not(cellfun('isempty', idx)));
Mineralienanzahl_RL=length(idx);
I appreciate every help :-) Thank you a lot

Accepted Answer

Stephen23
Stephen23 on 19 Jul 2022
Edited: Stephen23 on 19 Jul 2022
want = "Gruppe 1; Gruppe 2; Gruppe 3; Gruppe 3; ; Gruppe 6";
vgls = "Gruppe 1; Gruppe 2; Gruppe 3; Gruppe 4; Gruppe 5; Gruppe 6; Gruppe 7";
wc = regexp(want,'\w+\s+\d+','match')
wc = 1×5 string array
"Gruppe 1" "Gruppe 2" "Gruppe 3" "Gruppe 3" "Gruppe 6"
vc = regexp(vgls,'\w+\s+\d+','match')
vc = 1×7 string array
"Gruppe 1" "Gruppe 2" "Gruppe 3" "Gruppe 4" "Gruppe 5" "Gruppe 6" "Gruppe 7"
[ix,iy] = ismember(wc,vc)
ix = 1×5 logical array
1 1 1 1 1
iy = 1×5
1 2 3 3 6
cn = hist(iy,1:numel(vc))
cn = 1×7
1 1 2 0 0 1 0
compose("%s: %d",vc(:),cn(:))
ans = 7×1 string array
"Gruppe 1: 1" "Gruppe 2: 1" "Gruppe 3: 2" "Gruppe 4: 0" "Gruppe 5: 0" "Gruppe 6: 1" "Gruppe 7: 0"
  5 Comments
Tatjana Mü
Tatjana Mü on 22 Jul 2022
@Stephen23 Thank you so much!! It works. You are a hero :-) Thaaaank you!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by