Help extracting data from 3D matrices
1 次查看(过去 30 天)
显示 更早的评论
Given a matrix A, such that size(A) = {m,n,l}, and a vector v: mx1,
I would like to obtain a 2D matrix F: mxn, in which:
each row of F is given by [i, : , v(i)].
And I would like to do this parametrically, with 1 line. An example to play with below.
m = 2;
n = 2;
l = 3;
A = [];
A(:,:,1) = [1 0;
0 0];
A(:,:,2) = [ 0 2;
0 0];
A(:,:,3) = [0 0;
3 0];
v = [2;3];
% I would like to obtain something like below, but parametrically and
% without for/if/etc.
F = [];
F(1, :) = squeeze(A(1, : , v(1)));
F(2, :) = squeeze(A(2, : , v(2)));
A
F
Thanks everyone,
E.
4 个评论
Dyuman Joshi
2023-11-8
"for loops and if logics break code execution and increase computation time considerably."
Do you have a source for this?
Yes, vectorization is faster than using loops, but that does not mean loops are slow.
Let's compare Voss's answer below to a for loop approach -
%Taking a big sample for proper testing
A = rand(2500,500,100);
v = randi(size(A,3),size(A,1),1);
fun1 = @() forloop(A,v);
fun2 = @() vectorization(A,v);
z1 = fun1();
z2 = fun2();
%Check for equality
isequal(z1,z2)
fprintf('Time taken by the for loop is %f secs', timeit(fun1))
fprintf('Time taken by the vectorized method is %f secs', timeit(fun2))
function F = forloop(A,v)
[m,n,l] = size(A);
F = zeros(m,n);
for k=1:m
F(k,:) = A(k,:,v(k));
end
end
function F = vectorization(A,v)
[m,n,l] = size(A);
idx = sub2ind([m,n,l],repelem(1:m,1,n),repmat(1:n,1,m),repelem(v(:).',1,n));
F = reshape(A(idx),[],m).';
end
As you can see from the above results, the for loop is the faster method here.
Though one can argue that there might be a better method utilizing vectorization, but the point I am trying to convey, is that vectorization being faster does not mean for loops are considerably slower (unless not used properly)
采纳的回答
Voss
2023-11-8
Here's one way:
A = cat(3,[1 0; 0 0],[0 2; 0 0],[0 0; 3 0]);
v = [2;3];
[m,n,l] = size(A);
idx = sub2ind([m,n,l],repelem(1:m,1,n),repmat(1:n,1,m),repelem(v(:).',1,n));
F = reshape(A(idx),[],m).';
disp(F);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!