0

我的代码是

 pathname=uigetdir;
 filename=uigetfile('*.txt','choose a file name.');
 data=importdata(filename);
 element= (data.data(:,10));
 in_array=element; pattern= [1 3];
 locations = cell(1, numel(pattern));
 for p = 1:(numel(pattern))
 locations{p} = find(in_array == pattern(p));
 end

 idx2 = [];
 for p = 1:numel(locations{1})
 start_value = locations{1}(p);
      for q = 2:numel(locations)

      found = true;

         if (~any((start_value + q - 1) == locations{q}))
         found = false;
         break;
         end

      end

    if (found)
      idx2(end + 1) = locations{1}(p);
    end

 end
[m2,n2]=size(idx2)

res_name= {'one' 'two'};
res=[n n2];

在这段代码中,我在数据文件的一列中找到了一个模式,并计算了它重复了多少次。

我有 200 个文件,我想对它们做同样的事情,但不幸的是我被卡住了。

这是我到目前为止添加的

 pathname=uigetdir;
 files=dir('*.txt');
 for k=1:length(files)
   filename=files(k).name;

    data(k)=importdata(files(k).name);

    element{k}=data(1,k).data(:,20);
    in_array=element;pattern= [1 3];
    locations = cell(1, numel(pattern));
    for p = 1:(numel(pattern))
    locations{p} = find(in_array{k}== pattern(p));
    end
    idx2{k} = [];

我怎样才能继续这段代码..??

4

1 回答 1

0

OK,首先定义这个函数:

function [inds, indsy] = findPattern(M, pat, dim)

    indices = [];

    if nargin == 2 
        dim = 1;
        if size(M,1) == 1
            dim = 2; end
    end

    if dim == 1        

        if numel(pat) > size(M,1)            
            return; end

        for ii = 1:size(M,2)
            inds = findPatternCol(M(:,ii), pat);
            indices = [indices; repmat(ii,numel(inds),1)   inds]%#ok
        end

    elseif dim == 2

        if numel(pat) > size(M,2)            
            return; end

        for ii = 1:size(M,1)
            inds = findPatternCol(M(ii,:).', pat);            
            indices = [indices; inds   repmat(ii,numel(inds),1)]%#ok
        end

    else

    end

    inds = indices;
    if nargout > 1        
        inds  = indices(:,1);
        indsy = indices(:,2);
    end

end

function indices = findPatternCol(col, pat)    
    inds = find(col == pat(1));
    ii = 1;
    prevInds = [];
    while ~isempty(inds) && ii<numel(pat) && numel(prevInds)~=numel(inds)
        prevInds = inds;
        inds = inds(inds+ii<=numel(col) & col(inds+ii)==pat(ii+1));
        ii = ii + 1;
    end
    indices = inds(:);
end

这很不错,但可能不是最有效的。如果性能成为问题,请从这里开始优化。

现在循环遍历每个文件,如下所示:

pathname = uigetdir;

files = dir('*.txt');
indices = cell(length(files), 1);
for k = 1:length(files)

    filename = files(k).name;    
    data(k) = importdata(files(k).name);

    array = data(1,k).data(:,20);
    pattern = [1 3];

    indices{k} = findPattern(array, pattern);

end

可以像这样找到模式的出现次数:

counts = cellfun(@(x)size(x,1), indices);
于 2012-10-11T15:33:45.513 回答