Open In App

How to Create a Matrix From a Nested Loop in MATLAB?

Improve
Improve
Like Article
Like
Save
Share
Report

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




% Matlab code for Nested loop
% Empty matrix
mat = [];
  
%nested loop
for i = 1:5    %outer loop for rows
    for j = 1:5    %inner loop for columns
        mat(i,j) = i+j;
    end 
end
%printing matrix
disp(mat)


Output:

Resultant matrix:

 

Create a matrix where each element represents (row-number % column-number).

Example 2:

Matlab




% MATLAB code for Nested for loop
% empty matrix
mat = [];
  
% Nested loop
for i = 1:5    %outer loop for rows
    for j = 1:5    %inner loop for columns
        mat(i,j) = mod(i,j);
    end 
end
  
% Printing matrix
disp(mat)


Output:

Resultant matrix:

 

Create a matrix where each element represents the exponential sum of the row and column numbers.

Example 3:

Matlab




% MATLAB code 
% empty matrix
mat = [];
  
%nested loop
for i = 1:3    %outer loop for rows
    for j = 1:3    %inner loop for columns
        mat(i,j) = exp(i+j);
    end 
end
%printing matrix
disp(mat)


Output:

Resultant matrix:

 



Last Updated : 01 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads