Find array elements that meet a condition an put them in a secondary array
조회 수: 5 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
Star Strider
2015년 12월 21일
The find and ind2sub will do exactly what you want:
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];
idx = find(A > 0.5);
[i,j,k] = ind2sub(size(A), idx);
B = [i j k A(idx)]
B =
3 1 1 0.6256
4 1 1 0.7802
2 2 1 0.9294
3 2 1 0.7757
4 3 1 0.5085
1 1 2 0.5108
2 1 2 0.8176
3 1 2 0.7948
4 1 2 0.6443
2 2 2 0.8116
3 2 2 0.5328
1 3 2 0.939
2 3 2 0.8759
3 3 2 0.5502
4 3 2 0.6225
댓글 수: 0
추가 답변 (4개)
Image Analyst
2015년 12월 21일
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]
댓글 수: 0
Azzi Abdelmalek
2015년 12월 21일
ll=find(A>0.5)
[ii,jj,kk]=ind2sub(size(A),ll)
out=[ii,jj,kk,A(ll)]
댓글 수: 0
Andrei Bobrov
2015년 12월 21일
t = A > .5;
[m,n,~] = size(A);
[ii,jj] = find(t);
B = [ii,rem(jj-1,n)+1,ceil(jj/n),A(t)];
댓글 수: 0
H R
2015년 12월 21일
편집: H R
2015년 12월 21일
댓글 수: 1
Star Strider
2015년 12월 21일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!