How to accelerate the running speed of this code?

조회 수: 5 (최근 30일)
Hancheng Zhu
Hancheng Zhu 2024년 10월 8일
답변: Voss 2024년 10월 11일
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