find sequence in a matrix
Ältere Kommentare anzeigen
Hi, it possibile to velocize it and avoid loop? (I will be a matrix .,not a single array)
(if is possible to use vectorization)
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0]
k=3;
for i=1:numel(I)
if i>=k+1
if I(i-1) && ~I(i) %%i want to find the first "1 0"
saved=i;
break;
end
end
end
saved
Akzeptierte Antwort
Weitere Antworten (4)
The first [1, 0] shows up at index 2, not 7. It also appears at index 6 and others.
Probably the simplest way (a single line of code) is to use strfind. (Yes it works with numbers as well as character strings).
% Set up parameters:
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0];
searchPattern = [1, 0];
% Now find all locations where the vector has values [1, 0]
indexes = strfind(I, searchPattern)
If you want the first location, just take indexes(1).
3 Kommentare
shamal
am 11 Mai 2025
Image Analyst
am 12 Mai 2025
Bearbeitet: Image Analyst
am 12 Mai 2025
You didn't explicitly say that. And by looking at your code, it only starts looking at values for i>=k+1, or 4, not 3. And then it looks like it finds the trailing 0, not the leading 1, so it finds index 7 rather than 6 which is where the [1,0] pattern starts. So it was kind of confusing to me. Not sure what you want exactly.
If you want to find the index of the trailing 0 after index 3, you can do
% Set up parameters:
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0];
k=3;
searchPattern = [1, 0];
% Now find locations where the array has values [1, 0]
indexes = strfind(I(k:end), searchPattern) + k
If you want to find the index of the leading 1 after index 3, you can do
% Set up parameters:
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0];
k=3;
searchPattern = [1, 0];
% Now find locations where the array has values [1, 0]
indexes = strfind(I(k:end), searchPattern) + k - 1
Either way, it's still simpler than the other solutions.
Matt J
am 12 Mai 2025
Simpler, but not as efficient. strfind() will not operate row-wise on a matrix. You will have to loop. Additionally, it will search the entire row, unlike the other solutions which will stop at the first occurence.
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0;0 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 0 1;1 1 0 1 0 1 0 0 0 1 0 1 0 0 1 1 1 0]
k=3;
[minval,loc]=min(diff(I(:,k:end),1,2),[],2);
loc(minval>-1)=nan;
loc=loc+(k-1)
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0;0 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 0 1;1 1 0 1 0 1 0 0 0 1 0 1 0 0 1 1 1 0];
k=3;
Ik=string(char(I(:,k:end)+'0'));
loc=strlength(extractBefore( Ik , '10'))+k
I=[0 1 0 1 1 1 0 0 0 1 1 1 0 0 1 0 1 0;
0 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 0 1;
1 1 0 1 0 1 0 0 0 1 0 1 0 0 1 1 1 0]
k=3;
C=conv2(I,[0,1],'valid')./conv2(I,[1,1],'valid')==1
C(:,1:k-1)=0;
[~,loc]=max(C,[],2)
Kategorien
Mehr zu Geographic Plots finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!