How to accelerate the running speed of this code?
Show older comments
function [ S ] = fun(X,A,B,C)
%% obtain S from X
%% the size of X is A*B*C
S = zeros(A,B,C);
for a = 1:A
for b = 1:B
Z = X - X(a,b,:);
Z(a,b,:) = X(a,b,:);
S(a,b,:) = prod(Z,[1,2]);
end
end
end
I have a three dimensional matrix X (with dimension A*B*C) and I want to obtain a matrix S of the same dimension. This code is really time-consuming, but i don't know how to accelerate it. Is there any way possible to handle this problem?
1 Comment
Hancheng Zhu
on 9 Oct 2024
Answers (1)
Here's an approach that may or may not be faster (depending on the size of your array X) and may or may not run (depending on the size of X and how much RAM your machine has) but gives the same result as your original code.
X = rand(50,100,10);
S_old = fun_old(X);
S_new = fun_new(X);
isequal(S_old,S_new)
timeit(@()fun_old(X))
timeit(@()fun_new(X))
function S = fun_new(X)
[A,B,C] = size(X);
Z = X-reshape(permute(X,[3 1 2]),[1,1,C,A*B]);
[ii,jj,kk] = ind2sub([A,B,C],1:A*B*C);
mm = repmat(1:A*B,1,C);
idx = sub2ind([A,B,C,A*B],ii,jj,kk,mm);
Z(idx) = X;
S = reshape(permute(prod(Z,[1 2]),[4 3 1 2]),[A,B,C]);
end
function S = fun_old(X)
[A,B,C] = size(X);
S = zeros(A,B,C);
for a = 1:A
for b = 1:B
Z = X - X(a,b,:);
Z(a,b,:) = X(a,b,:);
S(a,b,:) = prod(Z,[1,2]);
end
end
end
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!