How to store data from a nested For loop
4 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
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
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);
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);
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);
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);
参考
カテゴリ
Help Center および File Exchange で Subplots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!