Lets Learn together... Happy Reading

" Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference "-Robert Frost

Number of occurrences in cell array

To find the number of occurrence of a string in an array:

Consider a cell array
c={'one';'two';'three';'nine';'five';'two';'six';'one'; 'two';'five';};


The number of times the string ‘one’ occurs in the array

sum(strcmp('one',c))

ans =

     2

To find the number of occurrence of all the elements in the array:


%c={'one';'two';'three';'nine';'five';'two'; 'six';'one'; 'two';'five';}; %dim=1

c='one','one','two','two','three','three','three','four','five','six','five','five'};%dim=2;

dim=2;
%Initialize the 'cell_array'
cell_array=cell([2 size(c,dim)]);
display(c);
inc=1;
for i=1:size(c,dim)
    %Compare the elements in the 'cell_array' with the elements in 'c'
   if(strcmp(cell_array(1,:),c(i))==0)
       %If the element is not present, then add it to 'cell_array'.
       cell_array(1,inc)=c(i);
       %Find the number of occurence of the element
     num=   sum(strcmp(c(i),c));
     cell_array(2,inc)=num2cell(num);
     inc=inc+1;
   else
       %Delete if the element is already present in the 'cell_array'.
       cell_array(:,inc)='';
      
      
   end
  
  
end

display(cell_array);



The result shows the elements in the first row and the number of occurrences in the second row.
like button Like "IMAGE PROCESSING" page

0 comments:

Enjoyed Reading? Share Your Views

Previous Post Next Post Home

Link

Related Posts Plugin for WordPress, Blogger...
Google ping Hypersmash.com