How to mark periods in my matrices?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello,
Since I am new in Data Analysis, I need some help marking periods of consecutieve 1's.
for i=1:length(PD)
for isessions=1:PD(i).TotSessionsVid
[PD(i).FakeMatrix(isessions).Random] = randi([0 1], 10000,4);
for iconfig=1:length(PD(i).FakeMatrix(isessions).Random)
if PD(i).FakeMatrix(isessions).Random(iconfig, :) == [1 1 1 1]
PD(i).FakeMatrix(isessions).Random2(iconfig, :) = [PD(i).FakeMatrix(isessions).Random(iconfig, :), 1];
elseif PD(i).FakeMatrix(isessions).Random(iconfig, :) == [1 1 1 0]
PD(i).FakeMatrix(isessions).Random2(iconfig, :) = [PD(i).FakeMatrix(isessions).Random(iconfig, :), 1];
elseif PD(i).FakeMatrix(isessions).Random(iconfig, :) == [1 1 0 0]
PD(i).FakeMatrix(isessions).Random2(iconfig, :) = [PD(i).FakeMatrix(isessions).Random(iconfig, :), 1];
elseif PD(i).FakeMatrix(isessions).Random(iconfig, :) == [1 0 1 0]
PD(i).FakeMatrix(isessions).Random2(iconfig, :) = [PD(i).FakeMatrix(isessions).Random(iconfig, :), 1];
else
PD(i).FakeMatrix(isessions).Random2(iconfig, :) = [PD(i).FakeMatrix(isessions).Random(iconfig, :), 0];
end
end
end
end
This is my code and my goal is to find for example 5 (or as many as I want) consecutieve 1's in the 5th column of the Random2 FakeMatrices. How can I do that? I have tried && statements combined with if statements, but I believe this can be more efficient. Can anyone help me? I want to mark them as 'on'.
4 Kommentare
Akzeptierte Antwort
jonas
am 23 Jul. 2018
Bearbeitet: jonas
am 24 Jul. 2018
If you have the image processing toolbox, you can use the function bwconncomp to find connected 1's. Using the example in the comments, this script finds segments where there are 3 or more consecutive 1's, and fills the output vector with 1's (indicating 'on')
CC=bwconncomp(M(:,5),4)
size(CC.PixelIdxList)
for i=1:numel(CC.PixelIdxList)
if numel(CC.PixelIdxList{i})>=3
out(CC.PixelIdxList{i})=1
end
end
If you do not have the image processing toolbox, you can use this solution instead.
%%Find at least 3 consecutive 1's
target=ones(1,3);
pos = strfind(M(:,5)',target);
out=zeros(size(M(:,5)));
for i=1:numel(pos)
out(pos(i):pos(i)+2)=1;
end
You can change the target to any number of consecutive 1's. You can also find other patterns, such as [1 0 1], but you will have to tweak the for-loop a bit.
4 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!