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
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개)
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)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!