Loops and conditional statement problem
显示 更早的评论
I've been trying to implement a set of loops and conditionals to carry out the following operation:
if sample(i+1)-sample(i) > value if this statement is true FOR AT LEAST 5 consecutive samples then fill another pre-allocated vector with the sample from point where true up until the point where not true.
Thanks for the help.
5 个评论
madhan ravi
2018-7-16
Can you show the example ?
Tom Shemeld
2018-7-16
J. Alex Lee
2018-7-23
A simple way to get as far as flagging positions where your condition is met without looping:
dVar1 = diff(Var1) % find differences between successive entries
flag = dVar1>10 % flag the positions where the difference is greater than 10
This gives you a logical array of length N-1, and now you have the problem of finding consecutive true's of length longer than 5...i found this interesting answer elsewhere: https://www.mathworks.com/matlabcentral/answers/366126-how-many-consecutive-ones
Matt C
2018-7-25
To build off the answer above, given the flag variable of logicals, this pseudo-code below could potentially solve your problem for actually copying over the parts of the vector that satisfy the condition.
% Track if the last seen element was zero.
lastSeenWasZero = true;
% Track how many consecutives ones have been seen.
oneCounter = 0;
for i = 1:length(flag)
% If last seen element was zero and current element is one, then save the beginning index of the sequence
if lastSeenWasZero && flag(i)
startSubsequence = i
end
% If the current element is one, then increment a counter of how many consecutive ones have been seen.
if flag(i)
lastSeenWasZero = false;
oneCounter = oneCounter + 1
end
% If element is zero, check if at least last 5 elements were ones. If so, then copy the elements which satisfied the condition over from one array to another.
if ~flag(i)
lastSeenWasZero = true;
if oneCounter >= 5
Var2(startSubsequence:startSubsequence+oneCounter) = Var1(startSubsequence:startSubsequence+oneCounter)
end
oneCounter = 0
end
end
%After hitting the end of the flags array, need to check if there were many ones all at the end of the vector.
if oneCounter >= 5
Var2(startSubsequence:startSubsequence+oneCounter) = Var1(startSubsequence:startSubsequence+oneCounter)
end
KALYAN ACHARJYA
2018-7-25
The question seems very easy, more clarification needed.
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!