Jason
Jason

Reputation: 1130

parallel programming in MATLAB

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.

Upvotes: 1

Views: 213

Answers (2)

Vahe Tshitoyan
Vahe Tshitoyan

Reputation: 1439

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};

Upvotes: 2

Siva Srinivas Kolukula
Siva Srinivas Kolukula

Reputation: 1241

You may follow something like below....

funcs = {@exp,@sin} ;
args = {2,pi/4} ;
sols = cell(1,2) ;
parfor n = 1:2
    sols{n}=funcs{n}(args{n});
end
M = sols{1} ; N = sols{2} ;

Upvotes: 1

Related Questions