Check if subsequent elements in a 3D matrix are the same value

조회 수: 3 (최근 30일)
mashtine
mashtine 2015년 8월 28일
댓글: mashtine 2015년 8월 28일
Hello,
I have a 121x97x51135 matrix of 1's and 0's which flag certain periods of time. I would like to produce new variables that count the number of times a 1 is followed by another in the subsequent element, and another if two ones follow in the subsequent 2 elements.
For instance:
if
A(:,:,1) = ones(3,3,1);
A(:,:,2) = ones(3,3,1);
A(:,:,3) = zeros(3,3,1);
A(:,:,4) = ones(3,3,1);
The output variable for the first test (1 followed by 1) would be a 3x3 matrix with a count of the number of times that occurred in A and thus result = ones(3,3).
Any suggestions how to do this with out a loop? Not sure if a function out there works for this. I tried diff() but diff won't work in terms of adding up these times. For instance:
diff(A,[],3)
ans(:,:,1) =
0 0 0
0 0 0
0 0 0
ans(:,:,2) =
-1 -1 -1
-1 -1 -1
-1 -1 -1
ans(:,:,3) =
1 1 1
1 1 1
1 1 1
Thanks in advance!
  댓글 수: 1
Stephen23
Stephen23 2015년 8월 28일
편집: Stephen23 2015년 8월 28일
Giving us the input values A to try is great, but we also need to know what your desired output data is. Showing us the not working diff is not so useful, because although it is in your mind it does not tell us what the correct answer should be. Please give exact example output values!
How many "tests" do you need to run?

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

채택된 답변

Stephen23
Stephen23 2015년 8월 28일
편집: Stephen23 2015년 8월 28일
>> Y2 = X(:,:,1:end-1) & X(:,:,2:end);
>> Y3 = X(:,:,1:end-2) & X(:,:,2:end-1) & X(:,:,3:end);
>> sum(Y2,3) % two consecutive "ones"
ans =
1 1 1
1 1 1
1 1 1
>> sum(Y3,3) % three consecutive "ones"
ans =
0 0 0
0 0 0
0 0 0
  댓글 수: 1
mashtine
mashtine 2015년 8월 28일
Thanks for this Stephen! I would have never have thought this was possible nor know how to find this. Very good use of logical indexing!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by