How to accelerate the running speed of this code for calculate a matrix?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Steven Lord
am 25 Feb. 2025
Bearbeitet: Walter Roberson
am 25 Feb. 2025
Why did you ask this as a separate question rather than following up on this post, which I believe is strongly related?
Antworten (1)
Deepak
am 26 Mär. 2025
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 Kommentare
Siehe auch
Kategorien
Mehr zu Adaptive Control finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!