MATLAB: How can this Python code be written in Matlab? I’m trying to write a Matlab script that will allow two Stepper motors to scan in a Raster pattern but all I can find is this Python script. How the ‘for’ loop be replicated in Matlab

matlab python raster pattern

from pylab import *
# define some grids
xgrid = arange(20, 31)
ygrid = arange(10, 16)
xscan = []
yscan = []
for i, yi in enumerate(ygrid):
xscan.append(xgrid[::(-1)**i]) # reverse when i is odd
yscan.append(ones_like(xgrid) * yi)
# squeeze lists together to vectors
xscan = concatenate(xscan)
yscan = concatenate(yscan)
# quick plot
plot(xscan, yscan, '.-')
axis([19, 31, 9, 16])
show()

Best Answer

There is a Cody question that asked you to produce a matrix like the one below
X=[1 2 3;
6 5 4;
7 8 9];
My solution was a variation of the code below
x_num_steps=round((xmax-xmin)/xstep)+1;
y_num_steps=round((xmax-xmin)/xstep)+1;
sort_order=reshape(1:(x_num_steps*y_num_steps),x_num_steps,y_num_steps)';
sort_order(2:2:end,1:end)=sort_order(2:2:end,end:-1:1);
You can use this matrix to sort your coordinate grid (which you can generate with meshgrid). (You will need to transpose it to get the correct order.) [X,Y]=meshgrid(linspace(xmin,xmax,x_num_steps),linspace(ymin,ymax,y_num_steps)); %vectorize and sort X and Y sort_order=sort_order(:); X=X(:);Y=Y(:); X=X(sort_order);Y=Y(sort_order);
So, here all of the code:
%initialize variables
ymin=0;
ystep=1;
ymax=1;
xmin=0;
xstep=1;
xmax=5;
%calculate the number of steps in each direction (i.e. grid lines)
%this also catches the case where the gap isn't an integer multiple of the step size
x_num_steps=round((xmax-xmin)/xstep)+1;
y_num_steps=round((xmax-xmin)/xstep)+1;
%create a matrix with 1:total number of steps (grid points)
sort_order=reshape(1:(x_num_steps*y_num_steps),x_num_steps,y_num_steps)';
sort_order(2:2:end,1:end)=sort_order(2:2:end,end:-1:1);
sort_order=sort_order';
%sort_order contains the order in which we should go through the X and Y matrices
[X,Y]=meshgrid(linspace(xmin,xmax,x_num_steps),linspace(ymin,ymax,y_num_steps));
%vectorize and sort X and Y
sort_order=sort_order(:);
X=X(:);Y=Y(:);
X=X(sort_order);Y=Y(sort_order);
%plot the line and zoom out a bit to show the path
plot(X,Y,'--')
axis([xmin-xstep xmax+xstep ymin-ystep ymax+ystep])