0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use Zeros in MATLAB: Syntax and Examples

In MATLAB, use the zeros function to create arrays filled with zeros. You specify the size as input, like zeros(3,4) for a 3-by-4 matrix of zeros.
๐Ÿ“

Syntax

The zeros function creates an array of zeros with the specified size.

  • zeros(n): Creates an n-by-n square matrix of zeros.
  • zeros(m,n): Creates an m-by-n matrix of zeros.
  • zeros([d1 d2 ... dn]): Creates an n-dimensional array of zeros with dimensions d1, d2, ..., dn.
matlab
Z1 = zeros(3);
Z2 = zeros(2,4);
Z3 = zeros([2 3 4]);
Output
Z1 = 0 0 0 0 0 0 0 0 0 Z2 = 0 0 0 0 0 0 0 0 Z3 is a 2x3x4 array of zeros
๐Ÿ’ป

Example

This example shows how to create a 3-by-5 matrix of zeros and display it.

matlab
A = zeros(3,5);
disp(A);
Output
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
โš ๏ธ

Common Pitfalls

Common mistakes when using zeros include:

  • Using non-integer or negative sizes, which causes errors.
  • Confusing zeros(n) with zeros(1,n) โ€” the first creates an n-by-n matrix, the second a 1-by-n row vector.
  • Forgetting to specify size as a vector for multi-dimensional arrays.
matlab
wrong = zeros(3.5,4); % Causes error
correct = zeros(3,4); % Correct usage
Output
Error using zeros Size inputs must be integers. correct = 0 0 0 0 0 0 0 0 0 0 0 0
๐Ÿ“Š

Quick Reference

Summary tips for using zeros:

  • Use integer sizes only.
  • Specify size as separate arguments or a size vector.
  • Use zeros(n) for square matrices.
  • Use zeros(m,n) for rectangular matrices.
  • Use zeros([d1 d2 ... dn]) for multi-dimensional arrays.
โœ…

Key Takeaways

Use the zeros function with size arguments to create arrays filled with zeros.
Specify sizes as integers; non-integers cause errors.
zeros(n) creates an n-by-n matrix, zeros(m,n) creates an m-by-n matrix.
For multi-dimensional arrays, pass a size vector like zeros([d1 d2 ... dn]).
Remember the difference between zeros(n) and zeros(1,n) for matrix vs vector.