Having trouble using for loops to create a matrix

4 次查看(过去 30 天)
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 个评论
Isabelle Davies
Isabelle Davies 2022-5-24
@Walter Roberson Would you mind elaborating on how to apply it? I looked at the function but I'm not sure how to apply it to this problem.

请先登录,再进行评论。

采纳的回答

Fabio Freschi
Fabio Freschi 2022-5-25
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(:),'.');

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by