MATLAB Answers

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

1 view (last 30 days)
Leif Jensen
Leif Jensen on 14 Apr 2021
Commented: Leif Jensen on 14 Apr 2021
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

Accepted Answer

John D'Errico
John D'Errico on 14 Apr 2021
Edited: John D'Errico on 14 Apr 2021
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 Comment
Leif Jensen
Leif Jensen on 14 Apr 2021
Thank you very much, this is exactly what I was looking for. Have a great day <3

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!