JavaScript nested for loops

3 visualizaciones (últimos 30 días)
Lu Ella
Lu Ella el 22 de Mzo. de 2021
Respondida: Arjun el 6 de Dic. de 2024

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.

Respuestas (1)

Arjun
Arjun el 6 de Dic. de 2024
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!

Categorías

Más información sobre Performance and Memory en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by