Having trouble using for loops to create a matrix
6 次查看(过去 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![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1008840/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1008840/image.png)
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 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!