Difference lower then 2 in one vector
Mostra commenti meno recenti
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
Risposte (1)
the cyclist
il 7 Feb 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 Commenti
Frantisek Stemberk
il 7 Feb 2021
Frantisek Stemberk
il 7 Feb 2021
Walter Roberson
il 7 Feb 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
il 7 Feb 2021
Frantisek Stemberk
il 7 Feb 2021
Walter Roberson
il 7 Feb 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
il 7 Feb 2021
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!