Using strfind in Matlab for different diagonal dir

2019-09-08 03:30发布

问题:

Before anyone asks, this is a repost of an earlier question, but I cannot delete it because it has answers, so I am modifying it so that hopefully Daniel R will answer it!

I have a grid of numbers and I want to read a string of numbers with strfind in any of the 8 directions. The non-diagonal ones I have managed to get to work fine, it is the diagonal ones that I have been struggling with (except for downRight which Daniel R helped me with earlier which I am very thankful for)!

Here is the code:

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 works, but I am not sure of how to get the others to work properly. Just to note, to test each direction the other 3 need to be commented out.

Thank you.

回答1:

A question personally addressing me, probably I must write an answer :)

Instead of implementing all 4 cases, I wrote a generic case. As you already noticed, the 4 cases can be produced using rot90 (rot90(X,0) does nothing).

To get the indices, I created a meshgrid which contains row- and columnnumbers. Simply put it through the same process of rot90 and diag, to see which index was moved to the position.

Finally, the outer loop (for r = 1:5) simply repeats everything.

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