Counting the appearance of a row in an array of row cells in Matlab

I have two cells of string arrays of different lengths, d = {'nerve', 'body', 'muscle', 'bone'} and e = {'body', 'body', 'muscle'}. I have to compare these two arrays and count the occurrences of each row in e in d. The expected result should be a vector, count_string = (0,2,1,0). Below is the code I wrote, but I get an error: assigning cell contents to an object not associated with a cell. I am new to programming at Matlab. Any quick help on this is greatly appreciated.

count_string=size(d)
for i=1:length(d)    
count_string{i}=sum(ismember(e{i},d));
end

After all your suggestions, this is the module that I have.

for i=1:length(d_union)
count_string1=cellfun(@(x) sum(ismember(d1,x)), d_union);
count_string2=cellfun(@(x) sum(ismember(d2,x)), d_union);
count_string3=cellfun(@(x) sum(ismember(d3,x)), d_union);
count_string4=cellfun(@(x) sum(ismember(d4,x)), d_union);
count_string5=cellfun(@(x) sum(ismember(d5,x)), d_union);
count_string6=cellfun(@(x) sum(ismember(d6,x)), d_union);
count_string7=cellfun(@(x) sum(ismember(d7,x)), d_union);
count_string8=cellfun(@(x) sum(ismember(d8,x)), d_union);
count_string9=cellfun(@(x) sum(ismember(d9,x)), d_union);
count_string10=cellfun(@(x) sum(ismember(d10,x)), d_union);
count_string11=cellfun(@(x) sum(ismember(d11,x)), d_union);
count_string12=cellfun(@(x) sum(ismember(d12,x)), d_union);
count_string13=cellfun(@(x) sum(ismember(d13,x)), d_union);
count_string14=cellfun(@(x) sum(ismember(testdoc,x)), d_union);    end   

matlab . 'd_union' 1x1216, d1-testdoc 1 × 240 . , . ? . .

+3
3

d e :

count_string = cellfun(@(x) sum(ismember(e,x)), d);

[0 2 1 0];

d ?

UPDATE

GRP2IDX HISTC. , e d.

[gi g] = grp2idx([d e]);
gn = histc(gi(numel(d)+1:end),1:numel(g));

g (, d), gn . gi - , .

GRP2IDX, , .

+3

count_string = cell(1,size(d));  

e, d.

for i=1:length(d)
   count_string{i}=sum(ismember(d{i},e));
end
+2

for-loop, macduff :

  • count_string CELL ZEROS:

    count_string = cell(size(d));   %# A 1-by-4 cell array
    %# OR
    count_string = zeros(size(d));  %# A 1-by-4 numeric array
    
  • When adding values ​​to count_stringyou must use ()-indexing for numeric arrays and {}-indexing for arrays of cells.

  • You need to change dboth eyour ISMEMBER call and the index dwith the loop variable instead e.

Regarding alternatives to using a loop, yuk gave you one solution using CELLFUN . Another vector solution is to use a combination of ISMEMBER and ACCUMARRAY :

>> [~, index] = ismember(e,d);  %# Find where each entry in e occurs in d
>> count_string = accumarray(index.', 1, [numel(d) 1]).'  %# Accumulate indices

count_string =

     0     2     1     0
0
source

All Articles