JavaScript nested for loops

3 ビュー (過去 30 日間)
Lu Ella
Lu Ella 2021 年 3 月 22 日
回答済み: Arjun 2024 年 12 月 6 日

I am new to coding. I need to create a code that prints a coordinate plane from (0,0) to (9,9). I then need to delete certain cells to make a diagonal line through the plane.

  1 件のコメント
darova
darova 2021 年 3 月 24 日
Any ideas?

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

回答 (1 件)

Arjun
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:');
Grid with Both Diagonals Removed:
for i = 1:gridSize
disp(grid(i, :));
end
" " "(0,1)" "(0,2)" "(0,3)" "(0,4)" "(0,5)" "(0,6)" "(0,7)" "(0,8)" " " "(1,0)" " " "(1,2)" "(1,3)" "(1,4)" "(1,5)" "(1,6)" "(1,7)" " " "(1,9)" "(2,0)" "(2,1)" " " "(2,3)" "(2,4)" "(2,5)" "(2,6)" " " "(2,8)" "(2,9)" "(3,0)" "(3,1)" "(3,2)" " " "(3,4)" "(3,5)" " " "(3,7)" "(3,8)" "(3,9)" "(4,0)" "(4,1)" "(4,2)" "(4,3)" " " " " "(4,6)" "(4,7)" "(4,8)" "(4,9)" "(5,0)" "(5,1)" "(5,2)" "(5,3)" " " " " "(5,6)" "(5,7)" "(5,8)" "(5,9)" "(6,0)" "(6,1)" "(6,2)" " " "(6,4)" "(6,5)" " " "(6,7)" "(6,8)" "(6,9)" "(7,0)" "(7,1)" " " "(7,3)" "(7,4)" "(7,5)" "(7,6)" " " "(7,8)" "(7,9)" "(8,0)" " " "(8,2)" "(8,3)" "(8,4)" "(8,5)" "(8,6)" "(8,7)" " " "(8,9)" " " "(9,1)" "(9,2)" "(9,3)" "(9,4)" "(9,5)" "(9,6)" "(9,7)" "(9,8)" " "
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!

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by