Difference lower then 2 in one vector
古いコメントを表示
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
回答 (1 件)
the cyclist
2021 年 2 月 7 日
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 件のコメント
Frantisek Stemberk
2021 年 2 月 7 日
Frantisek Stemberk
2021 年 2 月 7 日
Walter Roberson
2021 年 2 月 7 日
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
2021 年 2 月 7 日
Frantisek Stemberk
2021 年 2 月 7 日
Walter Roberson
2021 年 2 月 7 日
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
2021 年 2 月 7 日
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!