How to improve this function execution?

조회 수: 2 (최근 30일)
Elia Paini
Elia Paini 2022년 7월 19일
편집: Matt J 2022년 7월 21일
Hi, I have a code that includes a complex function which returns a column vector.
The function can be explained in this simplified form:
V = @(S1, S2, S3, S4, X1, X2, X3, X4) [...
a * S1/(S1 + S2) * X1;
b * X2;
c * S2/(S3 + S4) * X3;
d * S1/(S1 + S4) * X4;
....
];
where S and X are variables; a,b,c,d constants.
Since the code provides many calls of this function, and the profiler graph has clearly shown the large time necessary for its execution, how can I do to improve the performances?
I'm not interested to modify the overall code, but only the management of this function. Maybe, could I enter the function in different format (binary, csv,...) or as a file? Currently, the function is inside one of the code-related scripts (.m file).
Thanks
  댓글 수: 3
Elia Paini
Elia Paini 2022년 7월 19일
No, S and X are vectors
Matt J
Matt J 2022년 7월 19일
편집: Matt J 2022년 7월 19일
If they are vectors of the same size, the code you have posted will not evaluate the expressions element-wise (and will do something slower instead). If they are meant to be element-wise, then see my answer below.

댓글을 달려면 로그인하십시오.

답변 (1개)

Matt J
Matt J 2022년 7월 19일
편집: Matt J 2022년 7월 19일
Since the code provides many calls of this function
Instead of calling the function multiple times, call it just one time or just a few times but with vector inputs. To enable vectorized input, use .* and ./
[a,b,c,d]=deal(1);
V = @(S1, S2, S3, S4, X1, X2, X3, X4) [...
a .* S1./(S1 + S2) .* X1;
b .* X2;
c .* S2./(S3 + S4) .* X3;
d .* S1./(S1 + S4) .* X4
];
X1=rand(1,5);
X2=rand(1,5);
X3=rand(1,5);
X4=rand(1,5);
S1=rand(1,5);
S2=rand(1,5);
S3=rand(1,5);
S4=rand(1,5);
V(S1, S2, S3, S4, X1, X2, X3, X4)
ans = 4×5
0.0999 0.0116 0.1395 0.2693 0.1265 0.1044 0.8347 0.1419 0.0073 0.2531 0.0101 0.1552 0.1668 0.1691 0.1464 0.2829 0.2579 0.4367 0.7545 0.0059
  댓글 수: 2
Elia Paini
Elia Paini 2022년 7월 21일
편집: Elia Paini 2022년 7월 21일
Actually, S and X are elements (which form a vector).
But I need to consider them as elements, not vector, because of other aspects of the code
Matt J
Matt J 2022년 7월 21일
편집: Matt J 2022년 7월 21일
But I need to consider them as elements, not vector, because of other aspects of the code
That sounds doubtful. The better line of inquiry might be, do you really have to do that.
But anyway, the answer to your question is, no, you cannot speed up the execution if you must process the inputs as scalars, other than perhaps to use parallel computing toolbox functions like parfor.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with Optimization Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by