【问题标题】:Matlab - Multiplying a matrix with every matrix of a 3d matrixMatlab - 将矩阵与 3d 矩阵的每个矩阵相乘
【发布时间】:2014-01-09 21:13:23
【问题描述】:

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

  1. 我想找到最有效的方法(无循环?)将 (A x 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
    

【问题讨论】:

    标签: matlab matrix multiplication


    【解决方案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);
      

    【讨论】:

    • 第二个很漂亮,确实提高了我的表现。巧妙的把戏。第一个不是我想要的。我希望它不是逐元素乘法。另外,我想对返回的每个矩阵应用跟踪函数。我不认为我可以在评论中添加代码来向您展示。在我的第一个函数中,它是 for 循环之后的第一行(已被注释掉)。我想这部分是关于如何在没有循环的情况下在许多矩阵(第三维)上应用函数的更基本的问题。非常感谢您的帮助
    • @asdfa Thaks。很高兴我能帮上忙!
    猜你喜欢
    • 2015-01-24
    • 2016-12-11
    • 2018-07-09
    • 2022-06-30
    • 1970-01-01
    • 2012-01-31
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多