MATLAB Answers


How would I do this with a while loop script?

Asked by michael story on 16 Sep 2018 at 19:19
Latest activity Edited by Adam Danz
on 16 Sep 2018 at 21:13

I allow the user to input their own vector. Then my script shows the vector as a decimal number but with the integers as zeros. I now want my if statement showing if the vector has one or more numbers that are not integers as an incorrect input. I know how to get the script to display "incorrect input" but how would I get the part showing if the vector has one or more numbers that are not integers?


Sign in to comment.


1 Answer

Answer by Adam Danz
on 16 Sep 2018 at 19:25
Edited by Adam Danz
on 16 Sep 2018 at 20:01
 Accepted Answer

Use isinteger() which returns 0/1 for each element of the vector.

Then use any() to detect if there are any integers.


Note that this does not and should not be done in a loop.


so using a while-loop my script looks like the following: 1)vec=input('Please enter a vector consisting of integers:'); 2)while (blank) 3)vec(vec<0)=0 4)end 5)display('The decimal number:') .. So what would I want to put with the line along my while statement that is (blank)?

Now it's really unclear what you're trying to do. You're asking the user to enter integers and then you're trying to return the decimals to their input?

If I ignore all of that, this is how you can return a message to the command window and the results.

vec=input('Please enter a vector consisting of integers:'); 
fprintf('The decimal number: \n')

Note that the user will have to enter a vector using square brackets

[-1 -pi, 99, 42, -9.83]

or using colon operator

-5.5: 0.15 : 10

I have to write a script which I believe has to be a while loop since I have to ask the user if they want to repeat with "Enter 1 if you want to repeat".

One method would be to use a while loop. An alternative would be to write a nested function that prompts the user when called.

Second, the script should return the decimal number that is formed by replacing all negative numbers by zero such as [2 -3 4 -5] to 2040.

So, just to be clear from your example, 1) the user is expected to enter integers, 2) the integers will be concatenated for form 1 integer (negatives converted to 0), and 3) the decimal form will be returned which will always be 0?

Third, if the vector has one or more integers then it should result in an incorrect input.

Which, according to your example, will always be the case. Maybe there's a better example that will help.

Sign in to comment.