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
the cyclist 2021 年 2 月 7 日

0 投票

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
Frantisek Stemberk 2021 年 2 月 7 日
oh that makes sense, i’ll try that thank you!
Frantisek Stemberk
Frantisek Stemberk 2021 年 2 月 7 日
hello, so this script worked, thank you again
for i = 1:(length(yvars40)-1)
if yvars40(i) - yvars40(i+1) < 2
fvars40 = 1;
disp('fvars40=1')
else
fvars40 = 0;
disp('fvars40=0')
end
end
Now it types 1 if true or zero is false into command window, how would you store these values into one vector ? The vector for storing being the value fvars40.
Walter Roberson
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
Frantisek Stemberk 2021 年 2 月 7 日
yeah right, that is not really what i want, i want to find if there’s difference of 2 between 2 adjacent vector values and if there isn’t, the fvars vector will store 1 in itself, if yes then 0
Frantisek Stemberk
Frantisek Stemberk 2021 年 2 月 7 日
and it has to work for negative values too, haven’t considered that, can i solve it by typing the if condition like <+-2 ?
Walter Roberson
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
Frantisek Stemberk 2021 年 2 月 7 日
yes, it's only for < 2

サインインしてコメントする。

カテゴリ

質問済み:

2021 年 2 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by