Having trouble using for loops to create a matrix

조회 수: 7 (최근 30일)
Isabelle Davies
Isabelle Davies 2022년 5월 24일
답변: Fabio Freschi 2022년 5월 25일
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.
Walter Roberson
Walter Roberson 2022년 5월 24일
Stephen23 shows how to use it.

댓글을 달려면 로그인하십시오.

채택된 답변

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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by