How to speed up this array operation?

조회 수: 5 (최근 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 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