在单元格数组中查找上次连续出现

时间:2014-01-26 23:41:43

标签: matlab cell-array

我有一个如下所示的单元格数组:

Tickerarray = 

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

鉴于此单元格数组的某一列,我需要为每个条目找到包含该条目的最远(右侧)连续列。例如,给定此单元格数组的第一列,我想要一个输出:

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

鉴于第3列为输入,我想要输出:

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

1 个答案:

答案 0 :(得分:0)

可以使用strcmp或类似函数在单元格数组中进行字符串匹配,然后使用sum查找包含全零(无命中)的第一列(如果有)。< / p>

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