Question
I have data as follows (either numerical or logical, it doesn't matter in this case): [0 1 0 1 1 0 1 1 1 0 1 1 1 1 0] Every 0 represents one or more zeroes. I want to detect where consecutive sequences of ones are, but no longer than three after one another. I can do this imperatively with some for- or while-loop, walking over a window of five (?) elements, but I think that's computationally ineffective. How can I do this without loops, but with something like conv or movmean? The expected (logical) result for trains of nonzero values up to three long is [0 1 0 1 1 0 1 1 1 0 0 0 0 0 0] I know I can detect single peaks with: function tf = findsinglenonzeros(x) c = conv(double(x), [1, 1, 1], 'same'); tf = c & x == c; end But now for of nonzero values up to three (or n) long.
Expert Answer
Kshitij Singh
PhD Expert
Answered Aug 24, 2026
n=3; P=find(~[0 x(:).' 0]); d=diff(P)-1; idx=(d>=1)&(d<=n); locations=P( idx ); lengths=d(idx); z=zeros(1,numel(x)+1); z(locations)=1; z(locations+lengths)=-1; result =cumsum(z(1:end-1)),
100% Run Guarantee
3-Hour Fast-Track Delivery
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here
Related matlab Questions & Solutions
Browse All →
Explore similar technical troubleshooting questions and verified MATLAB solutions:
Ready-to-Run MATLAB & Simulink Projects
Browse All Projects →