Matlab循环不工作 [英] Matlab Loop not working
问题描述
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] );
如果isempty(正常)== 0;
rowOfFirstNum = r;
columnOfFirstNum = normal;
end
end
for diags = -5:5
downRight = strfind(diag(A,diags)',[10,9,19]);
ifempty(downRight)== 0;
rowOfFirstNum = downRight(1)+ max(-diags,0);
columnOfFirstNum = downRight(1)+ max(diags,0);
end
downLeft = strfind(diag(rot90(A),diags)',[11,2,9]);
如果isempty(downLeft)== 0;
rowOfFirstNum = downLeft(1)+ max(-diags,0);
columnOfFirstNum = downLeft(1)+ max(diags,0);
end
end
r对于downRight中的cOfFirstNum,但它总是5,也就是说for循环已经达到了最终值,然后它的值已经被赋值给cOfFirstNum,为什么这样呢?
基本上,你的错误是嵌套两个循环,内部循环检查对角线,并与检查行的外部循环无关:
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] );
如果isempty(正常)== 0;
rowOfFirstNum = r;
columnOfFirstNum = normal;
end
end
for diags = -5:5
downRight = strfind(diag(A,diags)',[10,9,19]);
ifempty(downRight)== 0;
rowOfFirstNum = downRight(1)+ max(-diags,0);
columnOfFirstNum = downRight(1)+ max(diags,0);
end
end
请仔细检查 rowOfFirstNum
和 columnOfFirstNum
,如果我的解决方案是正确的,则不能保证。
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?
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.
这篇关于Matlab循环不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!