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!
0 个评论
采纳的回答
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 个评论
更多回答(1 个)
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
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
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!