0
0
MATLABdata~5 mins

Special matrices (zeros, ones, eye, rand) in MATLAB

Choose your learning style9 modes available
Introduction

Special matrices help you quickly create common types of matrices like all zeros, all ones, identity, or random numbers. This saves time and makes your code easier to read.

When you need a matrix filled with zeros to start calculations.
When you want a matrix filled with ones for adding or multiplying.
When you need an identity matrix for linear algebra tasks.
When you want a matrix with random numbers for simulations or testing.
Syntax
MATLAB
zeros(n,m)
ones(n,m)
eye(n)
rand(n,m)

n and m are the number of rows and columns.

eye(n) creates an n x n identity matrix.

Examples
Creates a 3 rows by 4 columns matrix filled with zeros.
MATLAB
Z = zeros(3,4)
Creates a 2 by 5 matrix filled with ones.
MATLAB
O = ones(2,5)
Creates a 3 by 3 identity matrix with ones on the diagonal and zeros elsewhere.
MATLAB
I = eye(3)
Creates a 2 by 3 matrix with random numbers between 0 and 1.
MATLAB
R = rand(2,3)
Sample Program

This program creates four different 3x3 matrices using special matrix functions and prints them one by one.

MATLAB
% Create a 3x3 zero matrix
Z = zeros(3,3);

% Create a 3x3 ones matrix
O = ones(3,3);

% Create a 3x3 identity matrix
I = eye(3);

% Create a 3x3 random matrix
R = rand(3,3);

% Display all matrices
fprintf('Zero matrix:\n');
disp(Z);

fprintf('Ones matrix:\n');
disp(O);

fprintf('Identity matrix:\n');
disp(I);

fprintf('Random matrix:\n');
disp(R);
OutputSuccess
Important Notes

The rand function generates different numbers each time you run the program.

You can create square or rectangular matrices by changing n and m.

Use eye only for square identity matrices.

Summary

zeros creates a matrix filled with zeros.

ones creates a matrix filled with ones.

eye creates an identity matrix with ones on the diagonal.

rand creates a matrix with random numbers between 0 and 1.