How to improve this function execution?

2 views (last 30 days)
Elia Paini
Elia Paini on 19 Jul 2022
Edited: Matt J on 21 Jul 2022
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 Comments
Matt J
Matt J on 19 Jul 2022
Edited: Matt J on 19 Jul 2022
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.

Sign in to comment.

Answers (1)

Matt J
Matt J on 19 Jul 2022
Edited: Matt J on 19 Jul 2022
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 Comments
Elia Paini
Elia Paini on 21 Jul 2022
Edited: Elia Paini on 21 Jul 2022
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 on 21 Jul 2022
Edited: Matt J on 21 Jul 2022
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.

Sign in to comment.

Categories

Find more on Get Started with Optimization Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!