How to accelerate the running speed of this code for calculate a matrix?

10 ビュー (過去 30 日間)
Hancheng Zhu
Hancheng Zhu 2025 年 2 月 25 日
回答済み: Deepak 2025 年 3 月 26 日
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
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
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:
I hope this helps.

カテゴリ

Help Center および File ExchangeAdaptive Control についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by