mHelpMe
mHelpMe

Reputation: 6668

Get index position of where vector changes value

I have a vector that contains a list of strings which are ordered. I would like to know the index number of where the vector changes. Below is hopefully a clear example. I do not really use MATLAB much. In my head I'm just thinking of using a loop. I was wondering if there was a better way of doing this using MATLAB?

 Vector
 ABC
 ABC
 ABC
 ABC
 MNK
 MNK
 MNK
 PLO
 PLO

So I would like to know that ABC is from 1:4, MNK is from 5 : 7 & PLO is from 8 : 9

Upvotes: 2

Views: 132

Answers (1)

Divakar
Divakar

Reputation: 221624

One approach -

%%// Input
a1 = {
    'ABC'
    'ABC'
    'ABC'
    'ABC'
    'MNK'
    'MNK'
    'MNK'
    'PLO'
    'PLO'};

[val,x2] = unique(a1,'first');
[~,x12] = unique(a1); %%// By default takes the last unique value
out = [val num2cell(x2) num2cell(x12)]

Output -

out = 

    'ABC'    [1]    [4]
    'MNK'    [5]    [7]
    'PLO'    [8]    [9]

Upvotes: 5

Related Questions