Solving Input Issue in MATLAB Code

  • Thread starter Thread starter geft
  • Start date Start date
  • Tags Tags
    Input Matlab
AI Thread Summary
The MATLAB code initially fails to wait for user input due to the uninitialized variable 'ans', which should be set to a positive value before the while loop. The code also contains an invalid argument in the printf statement, which needs correction. To achieve accurate results, the total should be adjusted after the loop to exclude the terminating negative input. The user discovered that the input issue was specific to FreeMat, as the code functioned correctly in MATLAB. This highlights a known bug in FreeMat affecting the input() function.
geft
Messages
144
Reaction score
0
I have the following code which does not wait for input and skips right to the end. Is there something I miss?

Code:
no = 0;
total = 0;

while ans>=0
    ans = input('Input a number (negative to quit): ');
    no = no+1;
    total = total + ans;
end;

printf('\n');
disp('The input average is ');
total/no
 
Physics news on Phys.org
1) You need to initialize ans to a positive value to start with or your while statement will never be satisfied. You can subtract that value off later so it doesn't affect your count. 2) Your printf argument is not a valid character. I'm not sure what you had in mind there.
3) You'll get a cleaner output with the format in the last line below


no = 0;
total = 0;
ans = 1;

while ans>=0
ans = input('Input a number (negative to quit): ');
no = no+1;
total = total + ans;
end;
total = total - 1;

disp(['The input average is ',num2str(total/no)])
 
Thanks! I believe the input problem was because I was running the code on FreeMat. I tried running my original code on MATLAB and it worked. For some reason I can't get input() to work on FreeMat. EDIT: It's an existing bug.
 
Last edited:
Back
Top