Having trouble using for loops to create a matrix

8 views (last 30 days)
Hi there,
I'm currently trying to create two matrices that will be used for the x and y coordinates of particles in a random walks simulation.
I'm trying to make is so that the starting point of each particle is in a kind of grid formation, like in the photo below
This is what I have so far:
% a is length of axis on each side of origin
% b is gap between particles
% c is number of particles at each value of x or y
a = 25 ;
b = 5 ;
c = (2*a)/b - 1 ;
min = -a + b ;
max = a - b ;
particles = c^2; % total number of particles
steps = 250; % number of steps
Delta = 1; % size of jump
% x-coordinates are min:b:max
% y-coordinates are min:b:max
x = zeros(particles,steps+1) ;
y = zeros(particles, steps+1) ;
% So far, x amd y are both 81x1001 matrices
As you can see, I'm going for a 50x50 grid, with 25 on each side of both the x and y axes, and (0, 0) as the centre. I'm trying to get two matrices 'X' and 'Y' (one for each direction) where each row represents a single particle, and each column represents a step, so that the starting points of the particles will take up the first column of the matrix.
My goal is to get a matrix 'X' where the first nine (equal to c) rows/values in the first column are equal to -20 (equal to min), the next nine are equal to 20, and so on until the last nine are equal to 20 (max). For the 'Y' matrix, I'm trying to make it so that the columns of the first nine rows/values are -20, -15, -10, -5, 0, 5, 10, 15 and 20, and this pattern repeats nine times.
Below is the for loop I tried making so that I don't have to go through the process of assigning values for each group of nine for x and y, but I'm a bit stuck.
for n = 0:c-1
for m = min:5:max
y(1:c+(n*b):c^2,1) = m ;
end
end
Any help with this would be greatly appreciated!
  5 Comments

Sign in to comment.

Accepted Answer

Fabio Freschi
Fabio Freschi on 25 May 2022
I reproduce the result of the picture, because the question is not clear.
a = 25 ;
b = 5 ;
c = (2*a)/b - 1 ;
% do not use min/max as variable names
minVal = -a + b ;
maxVal = a - b ;
% x vector
x0 = minVal:b:maxVal;
% y vector
y0 = minVal:b:maxVal;
% create grid with meshgrid
[x,y] = meshgrid(x0,y0);
% plot
figure,plot(x(:),y(:),'.');

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by