given a large array of words and little cell how can i find for each word in the array the number of occurrences in the cell
2 次查看(过去 30 天)
显示 更早的评论
given alrage single array or cell :
A=['apple','bad','boring','car','champ','corn'...] /* about 4585 words no repetitions */
given a single cell :
b=['apple','champ','corn','apple','corn']
how can i get for each word in A how many it occurs in b /* in matlab*/
the result should be :
res=[2,0,0,0,1,2...]
witout using loops , loops in matlab take so much time .
your answers is super appreciated , thanks in advance .
0 个评论
采纳的回答
Benjamin Kraus
2017-12-26
Also, double-check your syntax for specifying a list of words. You need a cell-array of character vectors (using {}), or (starting in R2016b) a string array (using ""). If you copy/paste the code from your question into MATLAB, you will get a single concatenated character vector, which is probably not your intention.
3 个评论
Benjamin Kraus
2017-12-27
I noticed you revised your question, and separated the commands into command blocks. If you copy and paste that code into MATLAB, you will notice that it concatenates the strings instead of creates a list. Compare the output of the following three commands in MATLAB:
b = ['apple','champ','corn','apple','corn']
b2 = {'apple','champ','corn','apple','corn'}
b3 = ["apple","champ","corn","apple","corn"] % R2016b and newer
You will notice that 'b' is a single concatenated version of the strings. I do not think that is your intention.
Regarding ismember. If you call ismember, and provide both A and b:
[Lia,Locb] = ismember(A,b);
The first output will be a list of true or false for whether the elements of A are present in b. This tells you whether they are present, but not how many occurrences of each element.
If you call ismember and reverse the arguments:
[Lib,Loca] = ismember(b,A);
Assuming all the words in b are present in A, The first output, Lib, will be all true. The second output, Loca, gives you the index into A for each element of b. Then you can use another command, like accumarray to count how often each index occurs.
res = accumarray(Loca', 1, [numel(A) 1])';
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!