How to speed up this array operation?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Thilo Jürgens-Tatje
le 7 Mar 2021
Commenté : Walter Roberson
le 7 Mar 2021
I got the following function:
y = a.*x(1) + b.*x(2) + c
Where a, b and c are arrays of the length n.
So I get n equations. Now I can use fminsearch to find the minimum of the RMS of y. This works quite well.
But now I got two additional terms in each equation y(i), which are depending on the solution of the equation y(i-1).
I managed to write a working script by using a for loop, but its terribly slow.
function [rms] = Fun(x,a,b,c)
y(1)=0;
for i=2:length(a)
y(i) = a(i)*x(1) + b(i)*x(2) + c(i) + y(i-1)*x(3) + y(i-1)^2 *x(4);
end
rms = sqrt(mean(y.^2));
end
Is there a way to speed this process up? Maybe get rid of the for loop?
0 commentaires
Réponse acceptée
Walter Roberson
le 7 Mar 2021
Let's have a look:
N = 5;
syms x [1 N] real
syms a [1 N] real
syms b [1 N] real
syms c [1 N] real
syms y [1 N] real
y(1)=0;
for i=2:length(a)
y(i) = a(i)*x(1) + b(i)*x(2) + c(i) + y(i-1)*x(3) + y(i-1)^2 *x(4);
end
disp(y)
collect(y(end), x)
rms = sqrt(mean(y.^2));
disp(rms)
1 commentaire
Walter Roberson
le 7 Mar 2021
Now look at that collect(y(end),x) output. If, hypothetically, you could get rid of the for loop, it would have to be able to replicate that last entry in vectorized form. And, because you are asking for a faster way, it would have to do so faster than your current loop. When you look at the output, does that seem like realistic computation goals?
What you have looks like a non-linear filter, and because of the nonlinear feedback, you are pretty much stuck with loops unless you can find a way to make the theory of Difference Equations work for you.
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!