# MATLAB Basics

## Abstract

This is a quick tutorial for doing the basics in MATLAB.

Author(s): Mark A. Tschopp

## Variables

Variables can come in multiple forms in MATLAB, including:

• 8-bit and 16-bit integers, uint8 & uint16
• Single and double precision real numbers, single & double
• Logical or binary numbers, logical (0 or 1)
• Structured variables
• Scalar values, Vectors, or Matrices

Let's type in some commands at the command prompt.

 ```> a = 1666.67 a = 1666.67 ```

This command stores the variable 'a' in the variable stack with a value of 1666.67. It automatically assigns a class of real number to this variable. Also, notice that when you hit enter, 'a = 1666' is displayed below the command prompt. If you want to suppress output, put a semicolon after the command, i.e., 'a = 1666.67;'

You can change between variable formats using commands like:

 ```> b = uint8(a); > c = uint16(a); > d = double(b); ```

Notice that the variable b has a value of 255, c has a value of 1667, and d has a value of 255. The variable b is assigned 255, because 8-bit integers have values between 0 and 255. These are commonly used for images, where the intensity values typically run between 0 and 255.

Now, let's try to build a vector, e.

 ```> e = [1 2 3 5 8 13 21 34]; > e(1) 1 > e(2) 2 > e(5:8) [8 13 21 34] > e([1,3,5:8]) [1 3 8 13 21 34] ```

In the stack, the variable shows up as a 1x8 matrix. To access the first value, type 'e(1)'. The second value, 'e(2)', etc. We can also access multiple values, i.e., 'e(5:8)' where the 5:8 means 5, 6, 7, & 8. Some simple operations for vectors/matrices are 'sum', 'max', 'min', 'abs', e.g.,

 ```> f = sum(e) f = 87 > g = min(e) g = 1 > h = max(e) h = 34 > i = abs(e); ```

To transpose the matrix, use the transpose operator (apostrophe - '), i.e.,

 ```> [1 2 3 4] 1 2 3 4 > [1 2 3 4]' 1 2 3 4 ```

Now, let's try squaring each number, i.e.,

 ```> j = e.^2; > j(1) 1 > j(2) 4 ```

Let's now try Boolean operations to locate values.

 ```> k = e <= 3 k = [1 1 1 0 0 0 0 0] > l = e == 3 l = [0 0 1 0 0 0 0 0] > m = e > 3 m = [0 0 0 1 1 1 1 1] ```

Notice that there is a 1 wherever the logic statement is true and 0 wherever the logic statement is false. The variables k, l, and m are all logical arrays and can also be used to index values, e.g.,

 ```> e(k) [1 2 3] > e(l) 3 > e(m) [5 8 13 21 34] > e(~m) [1 2 3] ```

This can also be used to change specific values of an array, e.g.,

 ```> e = [1 2 3 5 8 13 21 34]; > e(k) = e(k) * 5 [5 10 15 5 8 13 21 34] > e(l) = 0 [5 10 0 5 8 13 21 34] > e(~k) = -1 [5 10 0 -1 -1 -1 -1 -1] ```

Value can also be deleted by using '[]'.

 ```> e = [1 2 3 5 8 13 21 34]; > e(4:6) = [] [1 2 3 21 34] ```

These rules also apply for 2-dimensional matrices, i.e.,

 ```> x = [1 2 3; 5 8 13; 21 34 55] 1 2 3 5 8 13 21 34 55 > x' 1 5 21 2 8 34 3 13 55 > n = x >= 13 0 0 0 0 0 1 1 1 1 > x(n) = x(n)+10 1 2 3 5 8 23 31 44 65 > sum(x) 37 54 91 > sum(sum(x)) 182 ```