How to Create a Matrix From a Nested Loop in MATLAB?
Last Updated :
01 Nov, 2022
Matrices are 2-dimensional arrays that store numeric or symbolic data. It is convenient to create them with the help of nested loops as the outer loop creates the elements along one dimension and the inner loop creates the elements along the second dimension. In this article, we will see how to create matrices from nested loops with various examples.
Create a matrix that has elements representing the sum of the row and column numbers where the indexing starts from 1.
Example 1:
Matlab
mat = [];
for i = 1:5
for j = 1:5
mat(i,j) = i+j;
end
end
disp(mat)
|
Output:
Resultant matrix:
Create a matrix where each element represents (row-number % column-number).
Example 2:
Matlab
mat = [];
for i = 1:5
for j = 1:5
mat(i,j) = mod(i,j);
end
end
disp(mat)
|
Output:
Resultant matrix:
Create a matrix where each element represents the exponential sum of the row and column numbers.
Example 3:
Matlab
mat = [];
for i = 1:3
for j = 1:3
mat(i,j) = exp(i+j);
end
end
disp(mat)
|
Output:
Resultant matrix:
Share your thoughts in the comments
Please Login to comment...