Difference lower then 2 in one vector
Mostrar comentarios más antiguos
So i have a sample data from simulink stored in a vector(yvars40), i have to find out if there are any elements next to each other with their difference lower than 2.If there are, value fvars40 types 1, else types 0, I came up with this but it doesn't work. Matlab says: 'Index exceeds the number of array elements.'
for i = length(yvars40)
if yvars40(i) - yvars40(i+1) < 2
fvars40 = 1;
else
fvars40 = 0;
end
end
Respuestas (1)
the cyclist
el 7 de Feb. de 2021
When you get to the last iteration of your loop
i == length(yvars40)
and therefore in your if statement, you try to compare the last element with the "next" element, which does not exist because you are at the end of the vector. Instead, maybe you need
for i = 1:(length(yvars40)-1)
7 comentarios
Frantisek Stemberk
el 7 de Feb. de 2021
Frantisek Stemberk
el 7 de Feb. de 2021
Walter Roberson
el 7 de Feb. de 2021
for i = 1:(length(yvars40)-1)
if yvars40(i) - yvars40(i+1) < 2
fvars40(i) = 1;
else
fvars40(i) = 0;
end
end
... Or you could
fvars40 = yvars40(1:end-1) - yvars40(2:end) < 2;
with no loop.
Question: you talked about a "difference" of 2. But consider that for [-5 1] you would be testing -5 - 1 < 2 which would be -6 < 2 and you would say that is true. Is that really what you want?
Frantisek Stemberk
el 7 de Feb. de 2021
Frantisek Stemberk
el 7 de Feb. de 2021
Walter Roberson
el 7 de Feb. de 2021
fvars40 = abs(yvars40(1:end-1) - yvars40(2:end)) < 2;
To confirm, a difference of exactly 2 is not to be included, right?
Frantisek Stemberk
el 7 de Feb. de 2021
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!