Matlab - 将矩阵与 3d 矩阵的每个矩阵相乘 [英] Matlab - Multiplying a matrix with every matrix of a 3d matrix
本文介绍了Matlab - 将矩阵与 3d 矩阵的每个矩阵相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个似乎密切相关的 matlab 问题.
I have two matlab questions that seem closely related.
我想找到最有效的方法(无循环?)将 (A x A) 矩阵与 3d 矩阵 (A x A x N) 的每个矩阵相乘.另外,我想对这些产品中的每一个进行跟踪.http://en.wikipedia.org/wiki/Matrix_multiplication#Frobenius_product
这是内部的frobenius产品.在我下面的蹩脚代码中,我使用的是更有效的辅助定义.
This is the inner frobenius product. On the crappy code I have below I'm using its secondary definition which is more efficient.
我想将向量 (N x 1) 的每个元素与其 3d 矩阵 (A x A x N) 的对应"矩阵相乘.
I want to multiply each element of a vector (N x 1) with its "corresponding" matrix of a 3d matrix (A x A x N).
function Y_returned = problem_1(X_matrix, weight_matrix)
% X_matrix is the randn(50, 50, 2000) matrix
% weight_matrix is the randn(50, 50) matrix
[~, ~, number_of_matries] = size(X_matrix);
Y_returned = zeros(number_of_matries, 1);
for i = 1:number_of_matries
% Y_returned(i) = trace(X_matrix(:,:,i) * weight_matrix');
temp1 = X_matrix(:,:,i)';
temp2 = weight_matrix';
Y_returned(i) = temp1(:)' * temp2(:);
end
end
function output = problem_2(vector, matrix)
% matrix is the randn(50, 50, 2000) matrix
% vector is the randn(2000, 1) vector
[n1, n2, number_of_matries] = size(matrix);
output = zeros(n1, n2, number_of_matries);
for i = 1:number_of_matries
output(:, :, i) = vector(i) .* matrix(:, :, i);
end
output = sum(output, 3);
end
推荐答案
我假设你的意思是元素乘法:
I assume you mean element-wise multiplication:
A = 10;
N = 4;
mat1 = randn(A,A);
mat2 = randn(A,A,N);
result = bsxfun(@times, mat1, mat2);
使用 bsxfun
和 permute
对齐尺寸:
Use bsxfun
with permute
to align dimensions:
A = 10;
N = 4;
vec1 = rand(N,1);
mat2 = randn(A,A,N);
result = bsxfun(@times, permute(vec1,[2 3 1]), mat2);
这篇关于Matlab - 将矩阵与 3d 矩阵的每个矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文