user6347077
user6347077

Reputation:

Count unique consecutive values in Matlab

I have a data column which includes string and integer values, as well as blank cells (see below). What I would like to do is count the number of occurrences of unique string and integer values, but only for those values which are preceded by a different/blank value. Is this possible in Matlab? Many thanks.

Example:

Red, Red, Red, [blank], 2, 2, 1, 1, 1, [blank], 1, 1, [blank], Red, Red, 1

Desired output:

Red = 2,
2 = 1,
1 = 3

Upvotes: 0

Views: 130

Answers (1)

nirvana-msu
nirvana-msu

Reputation: 4077

First find indices of the values you want to count - i.e. the first one, and those that differ from the preceding value and are non-blank. Then you need to count unique values in resulting subset. Small caveat is that you cannot simply use unique since data types as mixed. One way to get around it would be converting numbers to strings (that obviously assumes that you don't have strings which coincide with numbers). You can then use a combination of unique and accumarray to find unique values and their frequencies:

data = {'Red', 'Red', 'Red', [], 2, 2, 1, 1, 1, [], 1, 1, [], 'Red', 'Red', 1};

idx = [true, ~cellfun(@isequal, data(2:end), data(1:end-1)) & ~cellfun(@isempty, data(2:end))];
data_match = data(idx);

data_str = cellfun(@num2str, data_match, 'uni', false);
[~, ia, ic] = unique(data_str, 'stable');
values = data_match(ia)'
counts = accumarray(ic, 1)

values = 
    'Red'
    [  2]
    [  1]


counts =
     2
     1
     3

Upvotes: 1

Related Questions