How to store data from a nested For loop

조회 수: 4 (최근 30일)
Joel Olenga
Joel Olenga 2022년 6월 29일
댓글: Joel Olenga 2022년 6월 29일
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

채택된 답변

Pratyush Swain
Pratyush Swain 2022년 6월 29일
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.

추가 답변 (1개)

Voss
Voss 2022년 6월 29일
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
  댓글 수: 1
Joel Olenga
Joel Olenga 2022년 6월 29일
woww! I really appreciate the alternatives!

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

카테고리

Help CenterFile Exchange에서 Subplots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by