I have a MATLAB function running slow and I have identified two lines of code that are computationally intensive. I also found that these two lines of code don't rely on each other and can be parallelized. I'm wondering what's the best way to parallelize these two lines of code, say my code is like this:
function [y,x] = test1(a)
y = exp(a);
x = sin(a);
end
suppose a is a large matrix, then how to parallel compute y and x. Parfor is one way to do that, for example:
parfor i = 1:2
if i == 1
y = exp(a);
else
x = sin(a);
end
end
I feel that this way is too naive and am wondering whether there are other ways to solve this.
If you do not want to use the parfor, you can create a batch process for each function you want to execute on an individual worker.
a = 10;
% starts execution on separate workers
exp_handle = batch(@exp,1,{a});
sin_handle = batch(@sin,1,{a});
% waits ultil the first is complete and gets the result
wait(exp_handle);
yc = fetchOutputs(exp_handle); % cell
% waits until the second is complete and gets the result
wait(sin_handle);
xc = fetchOutputs(sin_handle); % cell
y = yc{1};
x = xc{1};