How to do this while loop

2 visualizaciones (últimos 30 días)
Robin Li
Robin Li el 5 de Mzo. de 2020
Comentada: Walter Roberson el 5 de Mzo. de 2020
  4 comentarios
Robin Li
Robin Li el 5 de Mzo. de 2020
And also, not only abs(A(1)-B(1)) is <= 1; it can also abs(A(2)-B(1)) is <= 1. Are there easy ways to do so?
Walter Roberson
Walter Roberson el 5 de Mzo. de 2020
Are you to produce a vector the same size as A? A vector the same size as B? Are you permitted to use vectorized operations at all?

Iniciar sesión para comentar.

Respuesta aceptada

Amit
Amit el 5 de Mzo. de 2020
We can do it in this way :
A = [1 2 3]; B = [2 4 5];
LenA = 1;
while LenA <= length(A)
if(A(LenA)-B)<=1
out = true;
break
else
out = false;
end
LenA =LenA+1;
end
disp(out)
Hope it helps.
  1 comentario
Walter Roberson
Walter Roberson el 5 de Mzo. de 2020
We discourage people from prividing complete solutions to homework problems.
Also, this code does not impliment the original requirement to use abs().
if(A(LenA)-B)<=1
A(LenA) would be a scalar, but B is a vector, so A(LenA)-B would be a vector, and the result of comparing to 1 would be a vector. if statements are only considered true if all elements of the array of values being tested are non-zero. The above code is therefore looking to see whether there is some element of A that is within 1 of every element of B. It is not at all clear to me that is what the homework is intended to test.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by