在matlab中封装代码

时间:2012-10-11 12:36:21

标签: matlab design-patterns

我的代码是

 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} = [];

我该如何继续这段代码.. ??

1 个答案:

答案 0 :(得分:0)

好的,首先定义这个功能:

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);