Crop matrix based on entries
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I am working with matrix that contains only zeros and ones. I am trying to find a way to crop the matrix to include only the parts of the image where there are ones.
[0,0,0,0,0,0,0,0,0,0;
0,0,0,0,0,0,0,0,0,0;
0,0,0,0,0,0,0,1,0,0;
0,0,1,0,0,0,0,0,0,0;
0,1,1,1,0,0,0,0,0,0;
0,0,0,1,0,0,0,1,0,0;
0,0,1,1,0,0,1,1,0,0;
0,0,0,1,0,0,1,1,0,0;
0,0,1,0,0,0,0,0,0,0;
0,0,0,0,0,0,0,0,0,0]
This is just an example of the matrix but I am really working with a 10000x10000 array. The ones are largely near the center of that image so I am trying to basically filter out all of the extraneous zeros. Any ideas on how I would accomplish this?
0 Commenti
Risposta accettata
Matt J
il 29 Mag 2021
Modificato: Matt J
il 29 Mag 2021
A=[0,0,0,0,0,0,0,0,0,0;
0,0,0,0,0,0,0,0,0,0;
0,0,0,0,0,0,0,1,0,0;
0,0,1,0,0,0,0,0,0,0;
0,1,1,1,0,0,0,0,0,0;
0,0,0,1,0,0,0,1,0,0;
0,0,1,1,0,0,1,1,0,0;
0,0,0,1,0,0,1,1,0,0;
0,0,1,0,0,0,0,0,0,0;
0,0,0,0,0,0,0,0,0,0];
I=find(any(A,2));
J=find(any(A,1));
A=A(min(I):max(I) , min(J):max(J))
3 Commenti
Image Analyst
il 29 Mag 2021
You could also skip the any() calls:
[r, c] = find(A); % Find all non-zero rows and columns.
ACropped = A(min(r):max(r), min(c):max(c));
Not sure which way is faster - you'd have to try both with tic() and toc() to see.
Matt J
il 30 Mag 2021
Modificato: Matt J
il 30 Mag 2021
Using any() is going to be much faster (EDIT: when there is a thin boundary of zeros) because it requires finding only the first 1 in the columns and rows of A.
A=randi([0,1],6000);
A([1:10,end-10:end],:)=0;
A(:,[1:10,end-10:end])=0;
timeTest(A)
When the boundary is thick (as seems to be the case for the OP), using any() is slower, but only because we are not given the matrix in sparse form.
A=randi([0,1],6000);
A([1:2500,end-2500:end],:)=0;
A(:,[1:2500,end-2500:end])=0;
timeTest(A)
timeTest(sparse(A))
function timeTest(A)
tic;
I=find(any(A,2));
J=find(any(A,1));
[a,b,c,d]=deal(min(I), max(I), min(J), max(J));
toc;
tic;
[r, c] = find(A); % Find all non-zero rows and columns.
[a,b,c,d]=deal(min(r), max(r), min(c), max(c));
toc
disp ' '
end
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!