简体   繁体   中英

Matlab 3D matrix multiplication

In Matlab, I have two m-by-n matrices X and Y, with n>m. I need to define a 3D m-by-m-by-n matrix Z whose components can be computed as

for i=2:m
    for j=i+1:m
        for k=1:n
            Z(i,j,k) = (Y(j-1,k)-Y(i-1,k))*X(j-1,k);
        end
    end
end

As these nested loops require a long computational time, I have been looking for a way to define the matrix Z using matrices multiplication, but I have not managed so far. Any suggestion?

You can simply remove the inner loop (over k ) by writing

Z(i,j,:) = (Y(j-1,:)-Y(i-1,:)).*X(j-1,:);

Note the .* element-wise multiplication. You can then proceed to remove additional loops in a similar manner.

But note that, most likely, your loop is slow because you don't preallocate the output array . Do this before the loop:

Z = zeros(m,m,n);

You can also gain a bit of speed by reversing the loop order, such that the first index is iterated over in the innermost loop, and the last index is iterated over in the outermost loop. This accesses the matrix data in memory order, making your cache more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM