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!