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?
댓글 수: 0
채택된 답변
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)
rms = sqrt(mean(y.^2));
disp(rms)
댓글 수: 1
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!