Solving Input Issue in MATLAB Code

  • Thread starter Thread starter geft
  • Start date Start date
  • Tags Tags
    Input Matlab
Click For Summary
SUMMARY

The forum discussion addresses an input issue in MATLAB code where the input function does not wait for user input, causing the program to skip to the end. The user discovered that initializing the variable 'ans' to a positive value resolves the issue, allowing the while loop to function correctly. Additionally, the user noted that the input function works properly in MATLAB but fails in FreeMat due to an existing bug. The discussion also highlights the importance of using valid printf arguments and provides a cleaner output format for displaying the average.

PREREQUISITES
  • Understanding of MATLAB programming syntax
  • Familiarity with control flow structures in MATLAB (e.g., while loops)
  • Knowledge of input and output functions in MATLAB
  • Basic debugging skills in MATLAB environment
NEXT STEPS
  • Research MATLAB input function usage and common pitfalls
  • Explore debugging techniques in MATLAB for troubleshooting code
  • Learn about differences between MATLAB and FreeMat environments
  • Investigate MATLAB's printf function and its formatting options
USEFUL FOR

MATLAB programmers, educators teaching programming concepts, and anyone troubleshooting input issues in MATLAB or similar environments.

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:

Similar threads

  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
9
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 3 ·
Replies
3
Views
3K
Replies
11
Views
4K