Solving Input Issue in MATLAB Code

  • Thread starter Thread starter geft
  • Start date Start date
  • Tags Tags
    Input Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
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: