【问题标题】:MATLAB: Extracting indices from 3D matrix for another 3D matrixMATLAB:从 3D 矩阵中提取索引以获取另一个 3D 矩阵
【发布时间】:2020-03-29 12:03:29
【问题描述】:

我有两个相同大小的 3D 矩阵 AB 和另一个相同大小的 3D 矩阵 I,其中包含与A 的第一个维度相对应的一些索引。我想做类似A(I)/B(I) 的事情。

具体来说,A(I(x,y,z),y,z) 除以B(I(x,y,z),y,z) 得到所有x,y,z。 我该如何快速完成,可能使用repmatsub2ind 或简单的逻辑索引?

我知道如何非常有效地处理二维矩阵。如果没有z 维度我会这样做:

dum_i = I+(x_size+1).*repmat(0:(y_size-1), x_size+1, 1);  % Create a linear index
C= A(dum_i)./B(dum_i);

【问题讨论】:

    标签: matlab matrix indexing


    【解决方案1】:

    由于 A 和 B 的大小相同,我假设您想要按元素划分 ./

    %Some random test data
    A=rand(3,4,5);
    B=rand(size(A));
    I=zeros(size(A));
    for d2=1:size(I,2)
        for d3=1:size(I,3)
            I(:,d2,d3)=randperm(size(I,1));
        end
    end
    %end of test data
    
    %Second and third dimension are to be indexed directly, use ind2sub to genertae matching indices
    [~,I2,I3]=ind2sub(size(A),1:numel(A));
    %Generate a linear index, which does "I(x,y,z),y,z"
    LI=sub2ind(size(A),I(:),I2(:),I3(:));
    %Make the index the right shape:
    LI=reshape(LI,size(A));
    %Now linear indexing can be used to permute A and B in the intended way.
    C=A(LI)./B(LI);
    

    要进一步提高性能,您可以:

    • 用一些 repmat 表达式替换 ind2sub 行。
    • 执行“C=A/B,C=C(I)”。这将是C2=A./B;C2=C2(LI);

    我想两者都会提高性能,但运行一些其他计算我目前无法衡量任何东西。

    【讨论】:

    • 这实在是太慢了……可以用repmat函数写吗?
    • 对于二维矩阵,这工作得非常快,我不知道如何处理 3D 矩阵:dum_i = i+(dim1+1).*repmat(0:(dim2-1), dim1 +1, 1); C=A(dum_i )./B(dum_i )
    • 2d 和 3d 矩阵的大小以及您使用的 MATLAB 版本是多少?
    • R2019b,对于尺寸为 100x100 的矩阵,我需要执行此过程一百万次。查看我在问题中的编辑可能会对您有所帮助。
    • 那么您的 3d 矩阵的尺寸是多少? 100x100x1000000?
    猜你喜欢
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2015-02-04
    • 2013-06-23
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多