2014-01-09 290 views
2

我有兩個似乎密切相關的matlab問題。Matlab - 將矩陣乘以3D矩陣的每個矩陣

  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

我假定你的意思逐元素乘法:

  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); 
    
+0

第二個是美麗的,真的提高了我的表現。整潔的把戲。第一個不是我正在尋找的。我希望它不是按照元素的乘法。另外,我想在每個返回的矩陣上應用跟蹤函數。我不認爲我可以在評論中添加代碼來向您展示。在我的第一個函數中,它是for循環之後的第一行(它被註釋掉了)。我想這是關於如何在沒有循環的情況下在許多矩陣(第三維)上應用函數的一個更基本的問題。非常感謝幫助 – asdfa

+0

@asdfa Thaks。很高興我能幫上忙! –