Help with nested for loop generating coordinates

Hello, I need to generate a list of coordinates for electrodes in an electrode array. I figured out how to do this with multiple separate for loops, but I want to find a more elegant way to do it with nested for loops
The array has 9 shanks, and each shank has 32 electrodes. I know (or can work out in my head) the xyz coordinates of the first electrode in each shank and I know the spacing between shanks and between electrodes So I created a vector with the xyz coordinates of the first electrode in the first shank
E1=[0.00470, 0.00470, 0]
Then created a for loop to iterate for the other 31 electrodes (since each electrode is 0.00005 metres further in the z axis):
for i=2:32
E1(i,:) = E1(1,:) + [0, 0, 0.00005*(i-1)]
end
I then created a second matrix and for loop for the second shank (notice the first coordinate of the first row has advanced by 0.00030 because this is the distance in the x axis between shanks 1 and 2)
E2 = [0.00500, 0.00470, 0]
for i=2:32
E2(i,:) = E2(1,:) + [0,0,0.00005*(i-1)]
end
I do this for all 9 shanks, changing the coordinates each time, and then concatenate the 9 arrays:
E = vertcat(E1,E2,E3,E4,E5,E6,E7,E8,E9]
I appreciate that this is a very long winded and clumsy way of doing it, so how can I create a nested for loop with one index for the shank number and a second index for the electrode number, cycling through each shank and each electrode and altering the coordinates as need to produce one continuous array of coordinates?

Answers (1)

The command you are looking for is meshgrid
% vectors with positions
x = 0.00470:.0003:.0071;
y = 0.00470;
z = 0:0.00005:.00155;
% grid generation (note tha y is fixed, and z and x are flipped)
[Z,Y,X] = meshgrid(z,y,x);
% electrodes
E = [X(:) Y(:) Z(:)]

5 Comments

Thanks for your answer Is there a reason why Z and X need to be flipped in the meshgrid command?
I should also mention that my y coordinates do vary, as the shanks are in a 3 by 3 grid in the xy plane. So as we pass from shank 1 to shank 9, the x and y coordinates will at points both go up and down (shank 3 is at x position 0.00530 and y position 0.00470, but shank 4 is at x position 0.00470 and y position 0.00500, and shank 8 is at x=0.00500 and y=0.00530), so I can’t simply create a grid with a linear increase in the coordinates.
I flipped X and Z to have the same order you got in your example. You can also use a varying y
Sure, but can I use an X and Y that vary nonlinearly i.e go up and then down and then up again?

Sign in to comment.

Categories

Products

Release

R2015b

Asked:

on 19 Oct 2019

Commented:

on 19 Oct 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!