How to accelerate the running speed of this code?

5 次查看(过去 30 天)
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 个评论
Hancheng Zhu
Hancheng Zhu 2024-10-9
Thanks for your reply, bro. I have tried your function, but the output is not the same as my first function. Could you please check whether there is wrong calculation in your function. Thanks again for your kindly help

请先登录,再进行评论。

回答(1 个)

Voss
Voss 2024-10-11
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)
ans = logical
1
timeit(@()fun_old(X))
ans = 0.4165
timeit(@()fun_new(X))
ans = 0.3371
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by