How to accelerate the running speed of this code for calculate a matrix?
조회 수: 8 (최근 30일)
이전 댓글 표시
function [ M ] = fun(X,A,B)
%% Calculate M from X
%% the size of X is A*B
M = zeros(A,B);
for a = 1:A
Z = X - X(a,:);
Z(a,:) = X(a,:);
M(a,:) = prod(X,1)./prod(Z,1);
end
end
Here X is a real number matrix with dimensional
, and the resulting matrix M is also a real number matrix with dimensional
and is derived from the above "fun" function. Is there any way to optimize the running speed of these codes since i need to use it many times?
댓글 수: 1
Steven Lord
2025년 2월 25일
편집: Walter Roberson
2025년 2월 25일
Why did you ask this as a separate question rather than following up on this post, which I believe is strongly related?
답변 (1개)
Deepak
2025년 3월 26일
We can optimize the running speed of the code by avoiding redundant calculations inside the loop. Instead of recalculating the column-wise product prod(X, 1) for each iteration, we precompute it once before the loop starts.
Additionally, we eliminate the need to repeatedly modify the matrix Z by directly subtracting the a-th row from all other rows in X, and then replacing the a-th row of Z with X(a,:). By performing these operations outside the loop and focusing on matrix-based calculations, we reduce the computational overhead and take advantage of optimized matrix operations of MATLAB, leading to faster execution.
Below is the sample MATLAB code to achieve the same:
function [ M ] = fun(X,A,B)
%% Optimized calculation of M from X
%% the size of X is A*B
prodX = prod(X, 1); % Pre-compute the product of each column of X
M = zeros(A, B); % Initialize the result matrix M
% Vectorized computation of M
for a = 1:A
% Construct Z by subtracting X(a,:) from each row of X
Z = X - X(a, :);
Z(a, :) = X(a, :); % Replace the a-th row of Z with X(a,:)
% Compute element-wise product ratio
M(a, :) = prodX ./ prod(Z, 1);
end
end
Please find attached the documentation of functions used for reference:
Array Indexing: https://www.mathworks.com/help/matlab/math/array-indexing.html
I hope this helps.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Adaptive Control에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!