MATLAB: Vector isn’t storing the values passed to it

vectorwhile loop

I am going to ask a user to give me positive numbers, and I will quit once the user enters a negative number. Then, I will display all the positive numbers that they had entered. The code reads find to me, but for some reason, the array is not putting in the first positive number that the user passes to it… Any ideas will be greatly appreciated. Thank you.
i=0;
answer='Enter a positive number: ';
x=input(answer);
while x>0
x=input(answer);
i=i+1;
A(i)=x;
end

Best Answer

pmt = 'Enter a positive number: ';
num = str2double(input(pmt,'s'));
vec = [];
while num>0
vec = [vec,num];
num = str2double(input(pmt,'s'));
end
And tested:
Enter a positive number: 5
Enter a positive number: 3
Enter a positive number: 1
Enter a positive number: -1
>> vec
vec =
5 3 1
Note that I used the 's' option and wrapped input in str2double, which avoids the unnecessary risk of the user inputting arbitrary code (which would then be executed by input) or unsuitable values.
Related Question