Create MATLAB Matrix with For Loop: Step-by-Step Guide
In Matlab, matrices can be created using a for loop. Here is a simple example demonstrating how to create a 3×3 matrix using a for loop.
% 创建一个3x3的矩阵
matrix = zeros(3,3);
% 使用for循环填充矩阵
for i = 1:3
for j = 1:3
matrix(i,j) = i + j;
end
end
disp(matrix);
In this example, a 3×3 zero matrix called “matrix” is first created. Then two nested for loops are used to iterate through each element of the matrix and set the value of each element to the sum of the row and column numbers. Finally, the generated matrix is displayed using the disp function.