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!