gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:16:21 25 4
gpt4 key购买 nike

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

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

    这是弗罗贝尼乌斯内积。在下面的蹩脚代码中,我使用了更有效的辅助定义。

  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. 使用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);

关于Matlab - 将矩阵与 3d 矩阵的每个矩阵相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com