How I can find the indices of 4 consecutive elements in the same row?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Osama Hussein
el 8 de Mzo. de 2016
Comentada: Image Analyst
el 8 de Mzo. de 2016
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 comentarios
Respuesta aceptada
KSSV
el 8 de Mzo. de 2016
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 comentarios
Más respuestas (1)
Image Analyst
el 8 de Mzo. de 2016
I offer a much simpler solution:
for row = 1 : size(SA, 1)
columns{row} = strfind(SA(row,:), [1,0,1,0])
end
3 comentarios
Stephen23
el 8 de Mzo. de 2016
Editada: Stephen23
el 8 de Mzo. de 2016
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
el 8 de Mzo. de 2016
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?
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!