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

oh that makes sense, i’ll try that thank you!
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.
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?
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
and it has to work for negative values too, haven’t considered that, can i solve it by typing the if condition like <+-2 ?
fvars40 = abs(yvars40(1:end-1) - yvars40(2:end)) < 2;
To confirm, a difference of exactly 2 is not to be included, right?
yes, it's only for < 2

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2021년 2월 7일

댓글:

2021년 2월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by