Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can calculate starting and ending indices of specific string in a cell array in MATLAB?

Suppose that we have this cell array:

strings = {'a'; 'a'; 'a'; 'a'; 'a'; 'a'; 'b'; 'b'; 'b'; 'b'; 'm'; 'm'; 'm'; 'm'};

I want something like this as the output:

a  1    6
b  7    10
m  11   14

The numbers are showing the start and ending indices of every unique string. However, this is just an example. My cell array has more than 100 unique strings. What would be an efficient way to do this in MATLAB?

like image 918
Eghbal Avatar asked Jan 25 '26 10:01

Eghbal


1 Answers

The outputs of unique should give you what you're looking for right out of the box:

strings = {'a'; 'a'; 'a'; 'a'; 'a'; 'a'; 'b'; 'b'; 'b'; 'b'; 'm'; 'm'; 'm'; 'm'};
[uniquestrings, start, bin] = unique(strings);

Where:

uniquestrings = 

    'a'    'b'    'm'


start =

     1     7    11


bin =

     1     1     1     1     1     1     2     2     2     2     3     3     3     3

While this works well for the data provided, I'd be curious to see a more 'real' representative data set to perhaps make the function more generic.

like image 152
sco1 Avatar answered Jan 28 '26 14:01

sco1