How can I avoid loop for code optimization?
1 view (last 30 days)
Bruno Luong on 29 Apr 2021
Edited: Bruno Luong on 29 Apr 2021
Use MultipleQR FEX (C compiler for MEX build is required, unless for Windows platform)
y = linspace(1,10,1000);
Y = reshape(y,1,1,);
z = zeros(size(Y));
Z = [1+z sin(Y);
n = size(Z,1);
R = reshape(R,n*n,);
X = prod(R(1:n+1:end,:),1)*(-1)^n;
Jan on 29 Apr 2021
Edited: Jan on 29 Apr 2021
Start with pre-allocating the output. Letting an array grow iteratively consumes a lot of resources, because Matlab has to create a new vector in each iteration.
Y = linspace(1,10,1000);
X = zeros(1, length(Y)); % Pre-allocation!!!
for m = 1:length(Y)
Z = [1, sin(Y(m)); 2, cos(Y(m))];
X(m) = det(Z);
The code can be simplified and no loop is required:
Y = linspace(1, 10, 1000);
X2 = cos(Y) - 2 * sin(Y);
isequal(X, X2) % TRUE
It is not useful to optimize a code, which is a massive simplification of the real code. Calling DET() for a 2x2 matrix is a waste of time, because DET([a,b; c,d]) is simply: q*c - b*d. So either your problem can be solved in a cheap way without a loop, or you have hidden the important parts by posting an example which has been simplified too much.