Code doesn't terminate in the way that I want
이전 댓글 표시
I have a loop which changes the value of a vector at each iteration of the loop. I don't want the values in the loop to get greater or smaller than predefined values. The code I'm using for this is:
if (min(u_new)<0.02 || max(u_new)>0.98)
return;
end
This doesn't seem to work. I thought that this would be a relatively simple thing to prgram but it's being stubburn.
답변 (1개)
Max Alger-Meyer
2022년 3월 8일
편집: Max Alger-Meyer
2022년 3월 9일
1 개 추천
So I'm not totally sure what you're asking the code to do, but using 'return' is going to end your script or function. If you just want to exit the loop, use 'break' instead. Alternatively, if you just want the loop to skip over the values that would fall outside of your desired range and keep iterating, you'd want to flip the signs in the 'if' condition and change the values in the body of the if statement, once the criteria are met. If you post additional code so I can see what you are trying to do I can help more.
댓글 수: 7
Matthew Hunt
2022년 3월 8일
Image Analyst
2022년 3월 8일
Looks like it should work. At the end of the loop, just before the if statement, put this:
fprintf('u_new = %f.\n', u_new);
Do you see any values outside the range? If you still have trouble, attach a mat file with m, alpha, beta, dr, D, w, r_ps, etc. in it so we can run your code.
Jan
2022년 3월 8일
@Matthew Hunt: Just a hint: There is a comment "For computational efficency". It is inefficient to calculate a constant repeatedly inside a loop. Move the line:
gamma = -2 * (dr / D) * (0.5 * alpha + beta / R_ps(n));
in front of the loop.
Is q a vector? Then q(i) is a scalar and there is no need to transpose it. But if q contains imaginary values, it matters that the ' operator is the conjugate transposition.
Matthew Hunt
2022년 3월 9일
Max Alger-Meyer
2022년 3월 9일
@Matthew Hunt Another thing that I notice is that you are calling 'norm(c)', but you're not setting that value to a variable, so that line isn't doing anything. Do you perhaps mean to do something like this? If this isn't the issue, I think we'd need a .mat file to test the code, or at least a more detailed description of the error that you're getting.
c=gamma*w.*q(i)';
norm_c = norm(c);
u_new=B_1*u_old(:,i)+norm_c;
Matthew Hunt
2022년 3월 9일
Jan
2022년 3월 9일
@Matthew Hunt: And it does break the loop, if the condition is met:
min(u_new)<0.02 || max(u_new)>0.98
If the loop is not left, the condition is not true. You wrote "This doesn't seem to work", but of course it works exactly as expected. The problem is, that your u_new has other values than you expect. You can check this by your own or provide the input values.
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!