How to accelerate the running speed of this code for calculate a matrix?
3 次查看(过去 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!