If loop giving me troubles
3 次查看(过去 30 天)
显示 更早的评论
So I'm trying to stop certain parts of my code if the matrix values are between -1 and 1, but it won't stop there... I'm using an if statement, and just can't figure out where I'm going wrong. Here is my code:
i = 1; dh = [0.01:0.01:50]; for j = 1:length(dh) Ortho_heights=[-(.7+dh(j)) -.7 0 .7 .7+dh(j)]; fprintf('\nGLARE, [45/-45/-45/45]\n\n'); fprintf('\nA Matrix\n'); A(:,:,i) = (Ortho_heights(2) - Ortho_heights(1)).*Qbar(:,:,i) + ... (Ortho_heights(3) - Ortho_heights(2)).*Qbar(:,:,i+1) + ... (Ortho_heights(4) - Ortho_heights(3)).*Qbar(:,:,i+2) + ... (Ortho_heights(5) - Ortho_heights(4)).*Qbar(:,:,i+3); display(A(:,:,i)); fprintf('\nB Matrix\n'); B(:,:,i) = (1/2)*... ((((Ortho_heights(2)).^2 - (Ortho_heights(1)).^2)).*Qbar(:,:,i) + ... (((Ortho_heights(3)).^2 - (Ortho_heights(2)).^2)).*Qbar(:,:,i+1) + ... (((Ortho_heights(4)).^2 - (Ortho_heights(3)).^2)).*Qbar(:,:,i+2) + ... (((Ortho_heights(5)).^2 - (Ortho_heights(4)).^2)).*Qbar(:,:,i+3)); if B(:,:,i) < 1*10^-6 B(:,:,i) = 0; end display(B(:,:,i)); fprintf('\nD Matrix\n') D(:,:,i) = (1/3)*... ((((Ortho_heights(2)).^3 - (Ortho_heights(1)).^3)).*Qbar(:,:,i) + ... (((Ortho_heights(3)).^3 - (Ortho_heights(2)).^3)).*Qbar(:,:,i+1) + ... (((Ortho_heights(4)).^3 - (Ortho_heights(3)).^3)).*Qbar(:,:,i+2) + ... (((Ortho_heights(5)).^3 - (Ortho_heights(4)).^3)).*Qbar(:,:,i+3)); % && (-1 < D(2,3,i)) && (D(2,3,i) < 1) if (-1 < D(1,3,i)) && (D(1,3,i) < 1) flag == 1; else flag == 0; end if flag == 1 break end end
0 个评论
采纳的回答
Nobel Mondal
2015-4-30
I agree with the previous comments. However, your problem is with the inappropriate use of assignment operator in the if-else loop.
Try this:
if (-1 < D(1,3,i)) && (D(1,3,i) < 1)
flag = 1; % Not ==
else
flag = 0;
end
2 个评论
Nobel Mondal
2015-4-30
I guess, we all have been there sometimes :)
I would also suggest the same thing as Thorsten mentioned in his answer. Try the break statement within the if block itself to avoid similar situation, if possible:
if (-1 < D(1,3,i)) && (D(1,3,i) < 1)
break
end
更多回答(2 个)
Thorsten
2015-4-30
编辑:Thorsten
2015-4-30
Your for loop uses j but in the if clause you check for i, which is always 1. Is that really what you intended to do? If so, your testvalue D(1,3,1) may never be within the limits.
BTW, you could write your code more succinctly as
testvalue = D(1,3,i);
if testvalue > -1 && testvalue < 1
break
end
0 个评论
Image Analyst
2015-4-30
Before the if, add these lines:
fprintf('D(2,3,%d) = %f\n', i, D(2,3,i));
fprintf('D(1,3,%d) = %f\n', i, D(1,3,i)); % Whichever row you want - 2 or 1.
and see what values of D it spits out to the command window. It must not be getting into that range. Otherwise give us Qbar so we can run your code.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!