Variable input to MATLAB function resets involuntarily inside while loop. How can I prevent it?
13 views (last 30 days)
Show older comments
I have written a function which takes in an integer (int8) as one of the inputs (called iscool). The function runs a while loop and I insert an if-check inside it to break out of the loop. The if-check checks the value of the iscool variable as well and sets the value of imarch to 0 to get out of loop. So basically, the code is something like this.
% Code_snippet
while (imarch == 1)
<some procedures not modifying iscool>
if ((iscool == 0) && (<other condition 1>) && (<other condition 2>))
imarch = 0;
elseif ((iscool == 1) && (<other condition 3>) && (<other condition 4>))
imarch = 0;
end
disp (strcat('Cooling index is: ',num2str(iscool)));
end
The output of the disp command in the first while-loop execution is 0 (which is the input), but it changes to 1 in the subsequent iteration and stays so after that. I have tried removing the if-elseif-end check and the value of iscool stays intact in that case, but I need to have the check in order to be able to get out of the loop. Any sort of help, particularly an insight into why the value might be changing would be great help. Thanks.
0 Comments
Answers (2)
John D'Errico
on 29 Mar 2015
So you have not provided us all of your code (which would probably be quite lengthy.) Just a shortened version that does what you think it should do. And then you are asking us why your actual code does something that you consider strange. How can we possibly know?
The only solution is for you to learn how to use the debugger. Step through the code line by line if necessary. Or, you can use dbstop to test for a certain event to happen and stop when it did, like a variable changing state. Then look to see what caused that to happen.
Image Analyst
on 29 Mar 2015
Why do both the "if" and the "elseif" set imarch to 0? Should one of them set it to 1?
Under what circumstances to you ever set imarch to 1 so that you can leave the loop?
2 Comments
Image Analyst
on 30 Mar 2015
OK, then it should work. So now read John's answer again. We can't fix code that is not broken (like the code you posted). And we can't fix code that we cannot even see (like your actual code that you would not post).
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!