How to speed up this array operation?

16 ビュー (過去 30 日間)
Thilo Jürgens-Tatje
Thilo Jürgens-Tatje 2021 年 3 月 7 日
コメント済み: Walter Roberson 2021 年 3 月 7 日
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?

採用された回答

Walter Roberson
Walter Roberson 2021 年 3 月 7 日
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)
ans = 
rms = sqrt(mean(y.^2));
disp(rms)
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 3 月 7 日
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.

サインインしてコメントする。

その他の回答 (1 件)

David Cazenave
David Cazenave 2021 年 3 月 7 日
... preallocating speeds up for loops.

カテゴリ

Help Center および File ExchangeNumeric Solvers についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by