2

このループをベクトル化しようとしています:

needle = [1 2 3];

haystack  = [0 0 1 2 3 0 1 2 3;
             0 1 2 3 0 1 2 3 0;
             0 0 0 1 2 3 0 0 0];

for ii = 1:3

    indices{ii} = strfind (haystack(ii,:), needle);

end

indices{:}

indicesneedle次に、の各行の開始位置が含まれますhaystack(行ごとに異なる回数になる可能性があります):

3 7
2 6
4

strfindベクトル化されている限り、任意のコマンドで実行できますが、そうである必要はありません。

4

4 に答える 4

0

ルイスが提案したように、対応する行番号を別のベクトルで見つけても問題ない場合は、これも使用できます-

%// Main portion
haystack_t = haystack';
num1 = strfind(num2str(haystack_t(:))',num2str(needle(:))');
col = rem(num1,size(haystack,2));
ind = floor(num1/size(haystack,2))+1;

%// We need to remove indices that get into account because of concatenation of all the numbers into one big string
rm_ind = col> (size(haystack,2) - numel(needle))+1;
col(rm_ind)=[];
ind(rm_ind)=[];

さまざまな針入力で実行 -

RUN1 (Original values):
needle =
     1     2     3
haystack =
     0     0     1     2     3     0     1     2     3
     0     1     2     3     0     1     2     3     0
     0     0     0     1     2     3     0     0     0
col =
     3     7     2     6     4
ind =
     1     1     2     2     3

RUN2 :
needle =
     1     2     3     0     1
haystack =
     0     0     1     2     3     0     1     2     3
     0     1     2     3     0     1     2     3     0
     0     0     0     1     2     3     0     0     0
col =
     3     2
ind =
     1     2
于 2014-03-08T08:34:59.577 に答える
0

for ループを使用したくない場合は、次のようにします。

 result = cellfun(@(row) strfind(row, needle), num2cell(haystack, 2), 'UniformOutput', 0);
于 2014-03-08T01:32:48.803 に答える