필터 지우기
필터 지우기

How I can find the indices of 4 consecutive elements in the same row?

조회 수: 1 (최근 30일)
I have a big binary matrix, and I try to find the indices of certain elements. Let's say for example I have this matrix
SA = [ 0 0 0 0 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 1;
1 0 0 0 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1;
0 1 0 0 0 0 1 0 1 1 1 0 1 0 1 0 0 1 1 1];
each 4 consecutive elements is considered together, so how I can find the indices of 1 0 1 0? I just need the indices for the first element, and assume no repetition for the same consecutive 4 elements!

채택된 답변

KSSV
KSSV 2016년 3월 8일
clc; clear all
SA = [ 0 0 0 0 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 1;
1 0 0 0 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1;
0 1 0 0 0 0 1 0 1 1 1 0 1 0 1 0 0 1 1 1]; % Your matrix
[m,n] = size(SA) ; % Dimensions of your matrix
B = [1 0 1 0] ; % Matrix to compare
myidx = [] ; % Initialize your indices needed
% Loop for each row and column
for i = 1:m
for j = 1:n-length(B)
if SA(i,j) == B(1)
if SA(i,j+1)==B(2) && SA(i,j+2) == B(3) && SA(i,j+3) == B(4)
myidx = [myidx ; [i,j]] ;
end
end
end
end
  댓글 수: 2
Osama Hussein
Osama Hussein 2016년 3월 8일
Thank you, The code works, I just need to choose the indices which begins at 1 or 5 or 9 ... since each 4 consecutive elements are together. I think I can do this, Thank you very much :)
Stephen23
Stephen23 2016년 3월 8일
See Image Analyst's answer for a much faster and neater solution.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2016년 3월 8일
I offer a much simpler solution:
for row = 1 : size(SA, 1)
columns{row} = strfind(SA(row,:), [1,0,1,0])
end
  댓글 수: 3
Stephen23
Stephen23 2016년 3월 8일
편집: Stephen23 2016년 3월 8일
Columns is simply a cell array of the column indices. You could even do it on one line using cellfun:
col = cellfun(@(v)strfind(v,[1,0,1,0]),num2cell(SA,2),'Uni',0);
The answer you accepted has two nested loops, thirteen lines of code, and multiple temporary variables. MATLAB code does not need to be so complicated to perform trivial tasks like this!
Image Analyst
Image Analyst 2016년 3월 8일
Thanks Stephen. Osama, look at the output of it:
columns =
[11] [15] [1x2 double]
So columns{1} tells where 1 0 1 0 shows up in row #1. You can see that that happens at column #11 in row #1. So that one is correct.
columns{2} tells where 1 0 1 0 shows up in row #2. You can see that that happens at column #15 in row #2. So that one is also correct.
columns{3} is a 2 element array which is [11, 13]. It tells where 1 0 1 0 shows up in row #3. You can see that that happens both at column #11 and at column #13 in row #3. So that one is also correct.
So why do you think it may be giving you the wrong answer? What columns do you think the pattern should show up in? What do you think the right answer should be?

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by