How can I make a conditional statement when using variables?

In my script I first defined a for loop:
for n = 1:inf
a = 10^(n+1);
b = 10*a;
so the for-loop assigns every iteration new values to my variables a and b.
Right after it I made an conditional statement:
if (a <= x)&&(x < b)
I want my value x (which I assign when activating the script) to lie between a and b. But matlab won't agree with me. It says:
Operands to the || and && operators must be convertible to logical scalar
values.
Error in palin (line 10)
if (a <= x)&&(x < b)
Though I thought values to the variables a and b were assigned earlier in the script, matlab would recognize these values. I was wrong. Does anybody has a suggestion what I could do to fix this error? I hope it is very easy to solve, so that soon someone will help me out of this. Thanks in advance.

 Respuesta aceptada

Wayne King
Wayne King el 24 de Dic. de 2013
Editada: Wayne King el 24 de Dic. de 2013
I'm guessing from the error message you report that x is a vector, not a scalar. From the code snippet you show, both a and b are scalars, x should be a scalar too.
So for example, look at the following
x = 10001;
for n = 1:3
a = 10^(n+1);
b = 10*a;
if (a <= x)&&(x < b)
disp('yes');
else
disp('no');
end
end
Now, if you try the above with x a vector
x = 10000:10004;
You'll get the error message you are seeing.

3 comentarios

Actually I worked with scalars too, but now it seems like the error was due to the fact that I sent n to infinity;
n = 1:inf
Because when I tried the same script with n = 1:3 it worked out well... It also seems to depend on which value for x I take, for some values I get the error, for others I don't. So now I'm guessing it has something to do with the rest of my script, so I will put some magic in there and I hope it then works out well. Thanks for your answer!
I find it hard to believe that having the upper limit as 3 or something else, like inf, would cause it to work or fail. My guess is that you're changing x inside the loop and that if n is more than 3 somehow x turns into a vector. Does x appear at all in the loop other than the if statement? If so, are you concatenating/appending to it?
Yes, I am doing some calculations with x inside the loop, but I'm not appending to it, in contrast I'm making the scalar a smaller scalar inside the loop. But for now I don't get the error anymore, so I guess I made some small mistake in the script. Thanks for thinking along with me!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 24 de Dic. de 2013

Comentada:

el 24 de Dic. de 2013

Community Treasure Hunt

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

Start Hunting!

Translated by