While loop problems finding lowesst value

11 vues (au cours des 30 derniers jours)
Marius Reikerås
Marius Reikerås le 27 Oct 2020
Modifié(e) : Adam Danz le 27 Oct 2020
Im writing a code to find the lowest value of x which is dividable by 11 and bigger than sqrt(132), x is also a odd number. I dont understand whats wrong with my code under. Any help is appreciated.
odd = rem(x, 2) ~= 0
while x > sqrt(132)
if x / 11
min x
else
fprintf('Try again/n')
end
end
  1 commentaire
S. Walter
S. Walter le 27 Oct 2020
Your if statement is incomplete - right now it just says: "If the array of x is divided by 11, give the minimum value of x". It doesn't even get to the else part.
You want your if statement to say something like "If x divided by 11 has no remainder, give me that value of that x", then check to make sure it's odd and bigger than sqrt(132).

Connectez-vous pour commenter.

Réponses (1)

Adam Danz
Adam Danz le 27 Oct 2020
Modifié(e) : Adam Danz le 27 Oct 2020
"I dont understand whats wrong with my code"
Let's go line-by-line.
odd = rem(x, 2) ~= 0
Odd numbers are whole numbers. rem(2.1, 2) equals 0.1 which is not equal to 0 and would be misclassified as odd. I guess that you want to force the user to provide an integer for x in which case you could throw an error if x is not an integer
assert(mod(x,1)==0, 'x must be an integer.')
or you could add an integer test to the condition,
odd = rem(x,2)~=0 & mod(x,1)==0;
while x > sqrt(132) ... end
  • What happens when x is less than sqrt(132)?
  • Your while-loop never changes the value of x so the while-loop will be infinite.
if x / 11
Is x scalar? Unless x=0, this condition will always be true. If-statements should contain a binary condition that tests for true or false. Any scalar other than 0 will satisfy this condition. If x is a vector or array the if-statement is even more problematic and should be replaced by indexing. If you want to test whether x is divisible by 11, use
mod(x,11)==0
min x
This is not correct matlab syntax. Look at the documentation for examples.
" Im writing a code to find the lowest value of x which is dividable by 11 and bigger than sqrt(132), x is also a odd number."
Assuming x is a vector, here are some test you can combine using indexing,
x = 1:1000;
idx0 = mod(x,1)==0; % is integer
idx1 = mod(x,11)==0; % divisible by 11
idx2 = x < sqrt(132); % less than sqrt 132
idx3 = mod(1:10,2)==1 % is odd
Now combine those indices to pull out values of x that satisfy all tests and apply min().

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by