MATLAB Answers

How to mark periods in my matrices?

조회 수: 8(최근 30일)
JamJan
JamJan 2018년 7월 23일
편집: jonas 2018년 7월 24일
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
JamJan
JamJan 2018년 7월 23일
for example: This could be the output of the Matrix:
col 1 col2 col3 col4 col5 col6
1 1 1 1 1 on
1 1 0 0 1 on
1 0 1 0 1 on
0 1 1 0 0 off
0 0 1 0 0 off
1 0 1 0 1 off
0 0 1 1 0 off
1 0 0 0 0 off
1 1 0 0 1 on
1 0 1 0 1 on
1 1 0 0 1 on
1 1 0 0 1 on
0 0 0 1 0 off
0 0 1 0 0 off
0 0 1 0 0 off
0 0 1 1 0 off

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

채택된 답변

jonas
jonas 2018년 7월 23일
편집: jonas 2018년 7월 24일
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
jonas
jonas 2018년 7월 24일
Ah yes, that's correct. Updated the solution!

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

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by