Store numbers in an array from user input
Show older comments
How would I store numbers into an array one at a time from a user input? Here is what I have, but I'm getting an error saying
count = 0;
while count < 10
x(count) = input('Input a number: ');
count = count + 1;
end
x = x(1:count);
Subscript indices must either be real positive integers or logicals.
Error in untitled2 (line 5) x(count) = input('Input a number: ')
5 Comments
Student
on 28 Mar 2018
Jake Gonzalez
on 3 Apr 2018
I would recommend using a for loop instead of a while here.
It seems like you are just waiting for the user to give 10 inputs, for which a for-loop is better practice. If you were to be looping until, for example, the sum of the user inputs is becomes greater than a number, that would be a better use for a while-loop.
It may not seem important now on something small like this, but good coding practice helps on any coding level.
Something like this:
for ii = 1:10
x(ii) = input('Input a number: ');
end
Connor Frederick
on 25 Aug 2020
How would I get it to ask for a different variable each time?
Say I wanted 4 input variables a, b, c, d. I am trying to get it to ask for each different variable subsequently.
so,
Input length a
Input length b
input length c
input length d
Rik
on 25 Aug 2020
An array is a much better idea. That way you don't need to generate the variable name later in your code when you want to use the values. Using an array also means you can easily count how many variables were entered, as you can just count the elements with numel.
Md Iqbal
on 24 Oct 2020
Store string in array from user input in matlab GUI
Answers (1)
Shivani Dixit
on 9 Jun 2021
In the above given code it is also possible to form the array while taking the input from the user.
Also in the below code given for reference, you need not worry about the count as it is not used for indexing and only for incrementing each time a value is given until upper limit (here, 10)
You can refer to the below code for the same :
count = 0;
x=[];
while count < 10
y = input('Input a number: ');
x=[x y];
count = count + 1;
end
x % prints out the array containing values given by user
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!