# Writing Vectors, Matrices, and Arrays

## Contents

## Constructing Vectors

You can create a vertical vector by using semicolons:

VectorExample1 = [2; 4; 6; 1; 3; 5]

VectorExample1 = 2 4 6 1 3 5

which is a 6x1 size matrix. You can also choose to create a horizontal vector by using spaces or commas:

VectorExample2 = [2 4 6 1 3 5] VectorExample3 = [2, 4, 6, 1, 3, 5]

VectorExample2 = 2 4 6 1 3 5 VectorExample3 = 2 4 6 1 3 5

which are both 1x6 size matrices.

## Constructing Matrices and Arrays

Combine semicolons and commas/spaces, you can freely create NxM matrices or arrays:

MatrixExample1 = [2 4 6; 1 3 5] MatrixExample2 = [2 4; 6 1; 3 5]

MatrixExample1 = 2 4 6 1 3 5 MatrixExample2 = 2 4 6 1 3 5

## Colon Operator

It is frequently useful to generate arrays of running indices by using the colon operator:

TryColon1 = [1:6] TryColon2 = 1:6

TryColon1 = 1 2 3 4 5 6 TryColon2 = 1 2 3 4 5 6

A more general construction involves two colons, with the syntax (Starting Value) : (Increment) : (No Larger Than)

TryColon3 = 1:1:6 TryColon4 = 1:2:6

TryColon3 = 1 2 3 4 5 6 TryColon4 = 1 3 5

Here are some examples of more complicated arrays of running indices:

SampleArray1 = [2:2:6, 1:2:6] SampleArray2 = [2:2:6; 1:2:6]

SampleArray1 = 2 4 6 1 3 5 SampleArray2 = 2 4 6 1 3 5

## Zero/Unit Arrays

It is considerably faster, less accident-prone, and much more convenient to predefine large arrays before using them. The
functions ** zeros** and

**work fantastic on defining arrays of zeros and ones:**

`ones`ZeroArray = zeros(2,3) OneArray = ones(2,3)

ZeroArray = 0 0 0 0 0 0 OneArray = 1 1 1 1 1 1

It also accepts the alternate syntax

Size = [2,3] ZeroArray = zeros(Size)

Size = 2 3 ZeroArray = 0 0 0 0 0 0

## Linearly/Logarithmically Spaced Vector

There are two handy MATLAB internal functions which creates vectors with equally spaced points between the range you want:
** linspace** and

**.**

`logspace`linearVec = linspace(0, 1, 5)

linearVec = 0 0.2500 0.5000 0.7500 1.0000

The function ** linspace(X1, X2, N)** generates

**linearly equally spaced points between**

`N`**and**

`X1`**. Note that if**

`X2`**<2 it returns**

`N`**. The default value of**

`X2`**is 100.**

`N`logVec = logspace(0, 1, 5)

logVec = 1.0000 1.7783 3.1623 5.6234 10.0000

The function ** logspace(X1, X2, N)** generates

**logarithmically equally spacedpoints between**

`N`**and**

`10^X1`**. Note that if**

`10^X2`**<2 it returns**

`N`**. The default value of**

`10^X2`**is 50.**

`N`## Exercise

Use colon operators to generate the following array:

A = 1 2 3 2 4 6 3 6 9