How to speed up this array operation?

5 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by