Matlab - 将矩阵与3d矩阵的每个矩阵相乘

时间:2014-01-09 21:13:23

标签: matlab matrix multiplication

我有两个似乎密切相关的matlab问题。

  1. 我想找到一种最有效的方法(没有循环?)将(A×A)矩阵与3d矩阵的每个矩阵(A x A x N)相乘。此外,我想了解每个产品的痕迹。 http://en.wikipedia.org/wiki/Matrix_multiplication#Frobenius_product

    这是内部frobenius产品。关于我在下面的糟糕代码,我正在使用更高效的二级定义。

  2. 我想将向量(N x 1)的每个元素与其3d矩阵(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
    

1 个答案:

答案 0 :(得分:1)

我认为你的意思是元素乘法:

  1. 使用bsxfun

    A = 10;
    N = 4;
    mat1 = randn(A,A);
    mat2 = randn(A,A,N);
    result = bsxfun(@times, mat1, mat2);
    
  2. 使用bsxfunpermute对齐维度:

    A = 10;
    N = 4;
    vec1 = rand(N,1);
    mat2 = randn(A,A,N);
    result = bsxfun(@times, permute(vec1,[2 3 1]), mat2);