Can I change a 3-tensor into a matrix by indexing with a matrix?
21 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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. :)
[~,I] = min(abs(A),[],3)
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))
I could have used ind2sub also, but why bother?
More Answers (0)
See Also
Categories
Find more on Annotations 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!