Search code examples
matlabcell-array

Find last consecutive appearance in cell array


I have a cell array that looks like the following:

Tickerarray = 

'MNST'    'MNST'    'MNST'    'ALGN'    'ALGN'
'GRA'     'VLO'     'GRA'     'SKS'     'SKS' 
'VLO'     'GRA'     'SKS'     'TSO'     'JDSU'
'TSO'     'TSO'     'TSO'     'VLO'     'TSO' 

Given a certain column of this cell array, I need to find for each entry the most distant (to the right) consecutive column that contains that entry. For example, given the first column of this cell array, I would want an output:

'3'
'3'
'2' % even though VLO appears in column 4, it does not appear consecutively
'5'

Given column 3 as input, I would want as output:

'1'
'1'
'3'
'3'

Solution

  • This can be done using strcmp or similar functions to do the string matching across your cell array, then using sum to look for the first column with all zeros (no hits) if any.

    c= 1; % which column do we want
    sArray = Tickerarray(:, c:End); 
    l = size(sArray,1); % how many rows
    
    % preallocating output array 
    out = ones(l,1).*size(sArray,2); 
    
    for n = 1:l
       str = sArray{n,1};
       x = strcmp(str, sArray); % is logical index of hits
       m = find(sum(x)==0,1); % find first column containing all zeros
       if ~isempty(m)  % else defaults to preallocated value
          out(n) = m-1; 
       end
    end