0

在有人问之前,这是对较早问题的重新发布,但我无法删除它,因为它有答案,所以我正在修改它,希望 Daniel R 能回答它!

strfind我有一个数字网格,我想从 8 个方向中的任何一个方向读取一串数字。我已经设法正常工作的非对角线,这是我一直在努力解决的对角线(除了downRightDaniel R 之前帮助我解决的问题,我非常感谢)!

这是代码:

A = [5,16,18,4,9;
    9,10,14,3,18;
    2,7,9,11,21;
    3,7,2,19,22;
    4,9,10,13,8]

for r = 1:5
    for diags = -5:5
        downRight = strfind(diag(A,diags)', [10,9,19]);
        if isempty(downRight) == 0;
            rowOfFirstNum = downRight(1)+max(-diags,0);
            columnOfFirstNum = downRight(1)+max(diags,0);
        end
        downLeft = strfind(diag(rot90(A),diags)', [11,2,9]);
        if isempty(downLeft) == 0;
            %rowOfFirstNum = 
            %columnOfFirstNum = 
        end
        upLeft = strfind(diag(rot90(A,2),diags)', [19,9,10]);
        if isempty(upLeft) == 0;
            %rowOfFirstNum = 
            %columnOfFirstNum = 
        end
        upRight = strfind(diag(rot90(A,3),diags)', [3,7,14,4]);
        if isempty(upRight) == 0;
            %rowOfFirstNum = 
            %columnOfFirstNum = 
        end
    end
end

downRight有效,但我不确定如何让其他人正常工作。请注意,要测试每个方向,需要注释掉其他 3 个方向。

谢谢你。

4

1 回答 1

1

一个亲自向我提出的问题,可能我必须写一个答案:)

我没有实现所有 4 个案例,而是编写了一个通用案例。正如您已经注意到的,这 4 个案例可以使用rot90(rot90(X,0)不做任何事情) 生成。

为了获得索引,我创建了一个包含行号和列号的网格。rot90简单的把它通过and的相同过程diag,看看哪个索引被移动到了该位置。

最后,外部循环 ( for r = 1:5) 只是重复所有内容。

A = [5,16,18,4,9;
     9,10,14,3,18;
     2,7,9,11,21;
     3,7,2,19,22;
     4,9,10,13,8];
[col,row]=meshgrid(1:size(A,1));


 x=[10,9,19];
% x=[11,2,9];
% x=[19,9,10];
% x=[3,7,14,4];
for diags = -5:5
    for direction=0:3
        loc = strfind(diag(rot90(A,direction),diags)', x);
        if ~isempty(loc)
            colT=diag(rot90(col,direction),diags);
            rowT=diag(rot90(row,direction),diags);
            rowOfFirstNum=rowT(loc)
            columnOfFirstNum=colT(loc)
            switch direction
            case 0
                %code for downRight
            case 1
                %code for downLeft
            case 2
                %code for upLeft
            case 3
                %code for upRight
            end
        end
    end
end
于 2013-12-12T22:49:44.473 回答