How to improve this function execution?

1 次查看(过去 30 天)
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 个评论
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 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by