How to store data from a nested For loop

4 views (last 30 days)
I have the following code that generate the coordinates of a square grid using nested for loops. How can I store all coordinates in xy_coord?
xy_coord = zeros(9,2);
x = -500:500:500; % X range
y = -500:500:500; % Y range
for i=1:3
for j=1:3
xy_coord = [x(i),y(j)]
end
end

Accepted Answer

Pratyush Swain
Pratyush Swain on 29 Jun 2022
Hi,
I beleive you can proceed in the following manner,
xy_coord = zeros(9,2);
x = -500:500:500; % X range
y = -500:500:500; % Y range
%keep a variable to iterate over the rows in xy_coord i.e 1-->9%
k=1;
for i=1:3
for j=1:3
%store the respective x and y coordinate in that designated row%
xy_coord(k,:) = [x(i),y(j)];
k=k+1;
end
end
Hope this helps.

More Answers (1)

Voss
Voss on 29 Jun 2022
x = -500:500:500; % X range
y = -500:500:500; % Y range
"The" MATLAB way:
[xx,yy] = meshgrid(x,y);
xy_coord = [xx(:) yy(:)];
disp(xy_coord);
-500 -500 -500 0 -500 500 0 -500 0 0 0 500 500 -500 500 0 500 500
Another way:
nx = numel(x);
ny = numel(y);
xy_coord = [];
for i=1:nx
for j=1:ny
xy_coord(end+1,:) = [x(i),y(j)];
end
end
disp(xy_coord);
-500 -500 -500 0 -500 500 0 -500 0 0 0 500 500 -500 500 0 500 500
Another way:
xy_coord = zeros(nx*ny,2);
count = 0;
for i=1:nx
for j=1:ny
count = count+1;
xy_coord(count,:) = [x(i),y(j)];
end
end
disp(xy_coord);
-500 -500 -500 0 -500 500 0 -500 0 0 0 500 500 -500 500 0 500 500
Another way:
xy_coord = zeros(nx*ny,2);
for i=1:nx
for j=1:ny
xy_coord(j+(i-1)*ny,:) = [x(i),y(j)];
end
end
disp(xy_coord);
-500 -500 -500 0 -500 500 0 -500 0 0 0 500 500 -500 500 0 500 500

Community Treasure Hunt

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

Start Hunting!