How to accelerate the running speed of this code for calculate a matrix?
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Steven Lord
le 25 Fév 2025
Modifié(e) : Walter Roberson
le 25 Fév 2025
Why did you ask this as a separate question rather than following up on this post, which I believe is strongly related?
Réponses (1)
Deepak
le 26 Mar 2025 à 9:21
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 commentaires
Voir également
Catégories
En savoir plus sur Adaptive Control dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!