MATLAB: Help Nested Foor Loop

for loopnested for loop

Hello, I need to move two linear stages. I am using a nested for loop:
Xstep= Xdist/(NstepsX-1);
x=XposStart(2):Xstep:XposEnd(2);
Ystep= Ydist/(NstepsY-1);
y=YposStart(2):Ystep:YposEnd(2);
for k2=1:numel(y)
ZaberMoveAbsolute(zaber, Yaxis, y(k2));
for k1 = 1 : numel(x)
ZaberMoveAbsolute(zaber, Xaxis, x(k1));
pause(2.0);
end
end
With this loop the X-axis linear stage moves along all the steps (pausing 2 secs after every step) and then the Y-axis moves on one step, and again the X-axis moves along all its steps and so on, until Y-axes reach its last position.
What I need is that the two stages move at the same moment: Ideally the stages should reach all the positions (combinations of y(k2) and k(k1)) randomly and not following an order: the X-stage moves one step then the Y-stage moves one step and they pause for 2 secs, then again the first stage moves another step and the Y-stage moves for another step, and so on. How can I modify the for loop to implement this?
Thank you.

Best Answer

nx = numel(x);
ny = numel(y);
nxy = nx*ny;
xys = [nx, ny];
visit_order = randperm(nxy);
for k = 1 : nxy
[k1, k2] = ind2sub(visit_order(k));
ZaberMoveAbsolute(zaber, Yaxis, y(k2));
ZaberMoveAbsolute(zaber, Yaxis, y(k2));
pause(2.0);
end
This visits all of the nodes in a random order.