While conditioning to any element of an array

11 views (last 30 days)
Hello,
I am trying to get an input as an array, then i want to check if every element of array suits the condition. If not i would like to ask for another input
Here is my code;
As you can see the input mass (ex. [ 1 2 3 4 5 ]) must be between 1-100. If any element does not satisfy this condition (ex. [1 2 -3 -4 500]), the program must again ask for the input.
When I write any kind of values MATLAB says there is a error at line 7 (line with while condition). It says "Operands to the || and && operators must be convertible to logical scalar values."
How can I avoid this error?
Thanks in advance.
mo = input('Enter values for mass (mo): ');
nmo = numel(mo);
k=1:nmo;
while mo(k)<1 || mo(k)>100
fprintf('Mass must be between 1-100.\n');
mo = input('Enter values for mass (mo): ');
end

Accepted Answer

Rik
Rik on 21 Apr 2019
You need to make sure you have a scalar condition, instead of having an array. The any and all functions are very useful in cases like this. For older releases the syntax below is not valid, so then you must use mo(:) instead of mo.
mo = input('Enter values for mass (mo): ');
while any(mo<1,'all') || any(mo>100,'all')
fprintf('Mass must be between 1-100.\n');
mo = input('Enter values for mass (mo): ');
end

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!