【问题标题】:Find last consecutive appearance in cell array查找单元格数组中的最后一个连续出现
【发布时间】:2014-01-26 23:41:43
【问题描述】:

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

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'

【问题讨论】:

  • 我认为您的示例输出中有一个额外的3。另外,给定一个不是 1 的列,您是否要考虑它左侧的列?即给定第 3 列作为输入,SKS 连续出现在第 5 列 - 是所需的输出 5?
  • 你是对的;我编辑了它。我不想考虑左边的列;我使用第 3 列添加了一个示例。

标签: matlab cell-array


【解决方案1】:

这可以使用strcmp 或类似函数在整个元胞数组中进行字符串匹配,然后使用sum 查找第一列全为零(无命中)(如果有)。

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

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多