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 件のコメント
Joel Olenga
Joel Olenga 2022 年 6 月 29 日
Thank you so much!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeSubplots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by