Find array elements that meet a condition an put them in a secondary array
Show older comments
Hello all, I have a 3D matrix A. For example suppose that A is as follows:
A(:,:,1) =
0.1835 0.0811 0.4359
0.3685 0.9294 0.4468
0.6256 0.7757 0.3063
0.7802 0.4868 0.5085
A(:,:,2) =
0.5108 0.3786 0.9390
0.8176 0.8116 0.8759
0.7948 0.5328 0.5502
0.6443 0.3507 0.6225
I want to find the elements in A that are >0.5 and put them in an array B. Each row of array B should be [i,j,k,value]. In above example my array B would be like:
3 1 1 0.6256
4 1 1 0.7802
2 2 1 0.9294
3 2 1 0.7757
...
After this I want to print array B as it is in a text file ('Example.txt'). Thank you for your help.
Accepted Answer
More Answers (4)
Image Analyst
on 21 Dec 2015
Here are two different ways, a for loop way, and a vectorized way:
A(:,:,1) =[...
0.1835 0.0811 0.4359
0.3685 0.9294 0.4468
0.6256 0.7757 0.3063
0.7802 0.4868 0.5085];
A(:,:,2) =[...
0.5108 0.3786 0.9390
0.8176 0.8116 0.8759
0.7948 0.5328 0.5502
0.6443 0.3507 0.6225]
% In tuitive brute force "for" loop way:
numRows = nnz(A(:)>0.5);
out = zeros(numRows, 4);
currentRow = 1
for z = 1 : size(A, 3)
for row = 1 : size(A, 1)
for col = 1 : size(A, 2)
if A(row, col, z) > 0.5
out(currentRow, 1:4) = [row, col, z, A(row, col, z)];
currentRow = currentRow + 1;
end
end
end
end
out
% Vectorized way:
bigA = A(A(:)>0.5);
actualSubscripts = find(A(:) > 0.5)
[row, col, z] = ind2sub(size(A), actualSubscripts)
out = [row, col, z, bigA]
Azzi Abdelmalek
on 21 Dec 2015
ll=find(A>0.5)
[ii,jj,kk]=ind2sub(size(A),ll)
out=[ii,jj,kk,A(ll)]
Andrei Bobrov
on 21 Dec 2015
t = A > .5;
[m,n,~] = size(A);
[ii,jj] = find(t);
B = [ii,rem(jj-1,n)+1,ceil(jj/n),A(t)];
1 Comment
Star Strider
on 21 Dec 2015
This seems to work (continuing my previous code):
Crows = (B(:,1)>2) & (B(:,2)<3); % Logical Vector: 1=Meets Criteria
C = [B(Crows,1) B(Crows,2) k(Crows) B(Crows,4)] % New Filtered Matrix
C =
3 1 1 0.6256
4 1 1 0.7802
3 2 1 0.7757
3 1 2 0.7948
4 1 2 0.6443
3 2 2 0.5328
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!