Can I change a 3-tensor into a matrix by indexing with a matrix?

조회 수: 26 (최근 30일)
Leif Jensen
Leif Jensen 2021년 4월 14일
댓글: Leif Jensen 2021년 4월 14일
The general problem I have is this: I have a 3-tensor A of size MxNx4. My goal is to create a Matrix B, where B(i,j) = A(i,j,argmin(abs(B),[ ],3)), so Element (i,j) of B is the absolut minimum of the elements of A at location (i,j,:) multiplied with its sign. Currently my code uses a for loop, but I would like to implement this faster and witout the loop. Is this possible?
Current code:
[K,I] = min(abs(A),[],3);
B = zeros(M,N);
for i = 1:M
for j = 1:N
B(i,j) = A(i,j,I(i,j));
end
end

채택된 답변

John D'Errico
John D'Errico 2021년 4월 14일
편집: John D'Errico 2021년 4월 14일
A = randn(4,4,3) % Not very creative in making up numbers. So sue me. :)
A =
A(:,:,1) = 0.4622 0.5856 0.1111 -0.2010 0.0358 -2.7861 -1.6445 0.7185 -0.5906 -0.6218 1.7746 1.2300 0.7294 -2.2847 0.4423 -0.0953 A(:,:,2) = -0.8908 0.5662 0.5428 1.0418 -0.7065 0.6806 0.5251 0.3021 -0.6683 0.8634 1.1750 -1.6716 -0.6397 0.2347 1.1293 -1.5891 A(:,:,3) = -1.7307 -0.3145 1.4038 0.8339 0.3275 0.4950 -1.5382 -0.3774 -0.5102 -0.0072 -0.1327 0.2439 0.4810 0.7095 -0.8032 -1.0081
[~,I] = min(abs(A),[],3)
I = 4×4
1 3 1 1 1 3 2 2 3 3 3 3 3 2 1 1
What is I? For every combination of row and column in A, this is the plane containing the min abs value of A. So just grab the indicated element directly, rather than the absolute value of the element, and then attaching the sign. But this requires indexing using a single index.
B = A((1:4)' + 4*(0:3) + 16*(I-1))
B = 4×4
0.4622 -0.3145 0.1111 -0.2010 0.0358 0.4950 0.5251 0.3021 -0.5102 -0.0072 -0.1327 0.2439 0.4810 0.2347 0.4423 -0.0953
I could have used ind2sub also, but why bother?
  댓글 수: 1
Leif Jensen
Leif Jensen 2021년 4월 14일
Thank you very much, this is exactly what I was looking for. Have a great day <3

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by