How to store data from a nested For loop
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Joel Olenga
le 29 Juin 2022
Commenté : Joel Olenga
le 29 Juin 2022
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 commentaires
Réponse acceptée
Pratyush Swain
le 29 Juin 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.
Plus de réponses (1)
Voss
le 29 Juin 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);
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);
Voir également
Catégories
En savoir plus sur Subplots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!