JavaScript nested for loops
3 ビュー (過去 30 日間)
古いコメントを表示
回答 (1 件)
Arjun
2024 年 12 月 6 日
I understand that you want to create a grid of co-ordinate points from (0,0) to (9,9) and then delete the diagonal elements to obtain the final grid.
In order to create a grid with co-ordinate points, since the grid is a 2-D grid you have to run 2 nested "for" loops or "while" loops to populate the grid entirely with the co-ordinate points and then after you have obtained this grid, again run a "for" loop to delete the elements on the primary and secondary diagonals. To identify primary and secondary diagonal elements use the following equations:
- Primary Diagonal: Elements with co-ordinates (i,i)
- Secondary Diagonal : Elements with co-ordinates (i,gridSize-i+1)
Note: "i" is the loop control variable.
Kindly refer to the code below for better understanding:
gridSize = 10;
% Initialize the grid with coordinate tuples
grid = strings(gridSize, gridSize);
% Fill the grid with coordinate tuples
for x = 1:gridSize
for y = 1:gridSize
% MATLAB uses 1-based indexing, adjust to 0-based
grid(x, y) = sprintf('(%d,%d)', x-1, y-1);
end
end
% Remove cells to create both diagonals
for i = 1:gridSize
grid(i, i) = " "; % Main diagonal
grid(i, gridSize - i + 1) = " "; % Secondary diagonal
end
% Display the modified grid
disp('Grid with Both Diagonals Removed:');
for i = 1:gridSize
disp(grid(i, :));
end
Kindly refer to the documentation of "for" loops for better understanding: https://www.mathworks.com/help/releases/R2021a/matlab/ref/for.html
I hope this will help!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Performance and Memory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!