user3071257
user3071257

Reputation: 37

Matlab Loop not working

Can someone please tell me why r in downRight is always going up to 5 when I have said to record it's value as soon as downRight is given a value?

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
   normal = strfind(A(r,:), [7,9,11]);
    if isempty(normal) == 0;
        rowOfFirstNum = r;
        columnOfFirstNum = normal;
    end
end
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 = downLeft(1)+max(-diags,0);
        columnOfFirstNum = downLeft(1)+max(diags,0);
    end
end

r should be 2 not 5 for cOfFirstNum in downRight, but it is always 5 i.e. the for loop has reached the end before it's value has been assigned to cOfFirstNum, why is this?

Upvotes: 0

Views: 187

Answers (2)

Olivier
Olivier

Reputation: 921

Your second loop doesn't depend on r:

for diags = -5:5
    downRight = strfind(diag(A,diags)', [10,9,19]);
    if isempty(downRight) == 0;
        rowOfFirstNum = downRight;
        columnOfFirstNum = r;
    end
end

So you are basically evaluating that statement five times:

downRight = strfind(diag(A,diags)', [10,9,19]);

and that statement is true for each "r-loop"

Upvotes: 1

Daniel
Daniel

Reputation: 36720

Basically, your error was to nest both loops, the inner loop checks for diagonals and has nothing to do with the outer loop which checks for rows:

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
    normal = strfind(A(r,:), [7,9,11]);
    if isempty(normal) == 0;
        rowOfFirstNum = r;
        columnOfFirstNum = normal;
    end
end
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
end

Please double-check rowOfFirstNum and columnOfFirstNum, not shure if my solution is correct.

Upvotes: 2

Related Questions