Multiply matrices in cell array by another matrix
2 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a matrix U of size [n, r] and cell array A of length m such that A{i} is a matrix of size [n, n] for every i. I would like to obtain a matrix AU of size [n, r, m] such that AU(:, :, i) = A{i} * U. I cannot save A as a 3d matrix and use pagemtimes because each A{i} is a sparse matrix. For the moment I just used a naive for loop
AU = zeros(n, r, m)
for i = 1:m
AU(:, :, i) = A{i} * U;
end
Is there a more efficient and/or more compact way of doing this?
Thanks,
Ivan
0 个评论
回答(3 个)
James Tursa
2023-10-27
编辑:James Tursa
2023-10-27
You may be stuck with the loop. There are ways to rearrange and stack things so that you can do everything in a single matrix multiply, but this will involve deep data copies of the sparse matrices and maybe you don't want that. What are the sizes involved? I.e., what are typical values of n, r, and m? Is U full or sparse?
*** EDIT ***
E.g.,
n = 3;
m = 3;
r = 2;
% generate sample inputs
A = arrayfun(@(k)sparse(rand(n)),1:m,'uni',false);
U = rand(n,r);
% Looping method
AU = zeros(n, r, m);
for i = 1:m
AU(:, :, i) = A{i} * U;
end
% Single matrix multiply method
AC = vertcat(A{:});
ACU = AC * U;
C = mat2cell(ACU,n*ones(m,1),r);
ACU = cat(3,C{:});
disp(AU)
disp(ACU)
disp(max(abs(AU(:)-ACU(:))))
So both methods can get the same result, but both methods require some deep data copying. You would have to run this with your actual variable sizes and sparsity to see if there is any benefit for the 2nd method. But my gut is there will be more data churning in the 2nd method giving you no performance benefit. The mat2cell( ) and cat( ) stuff could probably be combined into one step if I was more clever (easy to do in a mex routine in one step), saving you some time.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!