Reputation: 21
While (condition): {Move human-1 from a to b, total 5 steps } End
While (condition): {Move human-2 from c to d, total 3 steps } End
In the above code, the top while loop is executed first and after it's done the second loop executes. The question is, is there any way to run the two independent while loops simultaneously? I need to show the movement of humans in plot(). Both of them should move in the plot window at the same time.
Thank you!
Upvotes: 1
Views: 387
Reputation: 35
Try to see this: Time series animation in Matlab. I don't think you actually need the two while to run in parallel, but rather you need to plot the two paths simultaneously. You can store the steps as a time series and then using the reference in the link I attached for visualizing as a video simultaneously.
Upvotes: 1
Reputation: 25140
You can do this using a combination of parfeval
to launch the work in parallel, and DataQueue
to update the graphics while the execution is ongoing.
The idea with the DataQueue
is that each worker will send an update back to the client, and then the client connects up an afterEach
handler to update the graphics. Here's an example:
% Need a parallel pool of size at least 2
if isempty(gcp)
parpool('local', 2);
end
% Set up some simple graphics
ax = gca();
cla(ax);
ax.XLim = [-10 10];
ax.YLim = [-10 10];
hold on;
h1 = plot(0, 0, 'MarkerSize', 10, 'Marker', 'o');
h2 = plot(0, 0, 'MarkerSize', 10, 'Marker', '*');
% Set up a DataQueue to receive data from the workers.
dq = parallel.pool.DataQueue();
% Hook up afterEach so that iUpdate is called each time
% a worker calls "send"
afterEach(dq, @(data) iUpdate(data, {h1, h2}));
% Use parfeval to launch the work in parallel. Pass in the
% DataQueue so that the workers can send results back to the client
fut1 = parfeval(@iDoWork, 0, dq, 1);
fut2 = parfeval(@iDoWork, 0, dq, 2);
% This gets called each time a worker calls "send" - it
% updates one or other of the handles in the cell array
% h12
function iUpdate(data, h12)
h = h12{data(1)};
set(h, 'XData', data(2), 'YData', data(3));
end
% This is the function that the workers execute in parallel
% It performs a computation, and then sends the output
% to the DataQueue dq.
function iDoWork(dq, index)
count = 0;
xLoc = 0;
yLoc = 0;
while count < 100 && max(abs([xLoc, yLoc])) < 10
xLoc = xLoc + rand() - 0.5;
yLoc = yLoc + rand() - 0.5;
data = [index, xLoc, yLoc];
send(dq, data);
pause(0.1);
count = 1 + count;
end
end
Upvotes: 1