---
tags: Matlab Workshop
---
# Lesson 0: Desktop Basics
## Matlab installation
NTHU provide free Matlab version for students to download. If you need, please refer to the following link [here](https://learning.site.nthu.edu.tw/p/405-1319-113887,c11954.php?Lang=zh-tw).
## Default layout

The desktop includes these panels:
1. Current Folder — Access your files.
2. Command Window — Enter commands at the command line, indicated by the prompt (>>).
3. Workspace — Explore data that you create or import from files (variable explorer).
## Variables
As you work in MATLAB, you can issue commands that create variables in command window.
For example, create a variable named a by typing this statement at the command line:
```matlab
>> a = 1 % input
a =
1 % output
```
Create a few more variables.
```matlab
>> b = 2
b =
2
```
```matlab
>> c = a + b
c =
3
```
```matlab
>> d = cos(a)
d =
0.5403
```
If you don't understand how to use some specific built-in function (e.g., cos), you can type `help (function name)`.
```matlab
>> help cos
```

When you do not specify an output variable, MATLAB uses the variable ans (short for answer), to store the results of your calculation.
```matlab
>> sin(a)
ans =
0.8415
```
If you end a statement with a semicolon, MATLAB performs the computation, but suppresses the display of output in the Command Window.
```matlab
>> e = a * b;
```
You can recall previous commands by pressing the up- and down-arrow keys, ↑ and ↓. Press the arrow keys either at an empty command line or after you type the first few characters of a command. For example, to recall the command b = 2, type b, and then press the up-arrow key.
## Clear
`clc` is used to **cl**ear **c**ommand window.
`clear` is used to clear all the variables in the workspace.
`close all` is used to close all the figures (plots).
# Lesson 1: Datatypes and Operators
## I. Introduction
It is suggested that in front of the "main" script, you should add:
```matlab
clear
close all
% ... your code here
```
## II. Datatypes and Data structures
| **Category** | **Data Type** | **Description** | **Example** |
|-----------------------------|------------------------------------|---------------------------------------------------------------------------------|-------------------------------------------------|
| **Numeric Types** | **Single-precision floating-point**| 32-bit floating-point numbers used to represent real numbers with decimals. | `3.14f`, `-2.718f`, `1.0e-3f` |
| | **Double-precision floating-point**| 64-bit floating-point numbers used for higher precision real number calculations.| `3.141592653589793`, `2.718281828459045` |
| | **Integers** | Whole numbers without decimals, can be signed (positive or negative) or unsigned.| `5`, `-10`, `255` |
| **Non-Numeric Types** | **Characters** | Individual characters (single letters, numbers, or symbols) or sequences of characters (strings) represented by a single element.|`'A'`, `'9'`, `'#'`, `'MATLAB'` |
|| **Strings** | Sequences of characters (text), often used to store words, sentences, or data. | `"Hello, World!"` |
| | **Structures** | Data types that group related data with different types, accessed by named fields.| `s.name = 'John'; s.age = 25;` |
| | **Logical values** |`true` or `false`, used for logical operations in decision making.| `true`, `false`, `1`, `0` |
## Datatype
### 1. Numeric types
#### 1.1. **Single**-precision floating-point
In this example, we create a variable `y` and assign it the value of pi, but using the single-precision floating-point data type instead of the default double-precision type. This can be **useful for conserving memory** when working with very large datasets.
```matlab
>> y = single(3.14159265359);
>> class(y)
ans =
'single'
```
#### 1.2. **Double**-precision floating-point:
```matlab
>> x = 3.14159265359;
>> class(x)
ans =
'double'
```
#### 1.3. **Integers**: Matlab also supports several integer data types with varying bit widths (8, 16, 32, and 64 bits).
```matlab
>> a = int16(42);
>> class(a)
ans =
'int16'
>> b = int32(1000000);
>> class(b)
ans =
'int32'
```
### 2. Non-Numeric Types
#### 2.1. Character
```matlab
>> c = 'Hello, world!';
>> class(c)
ans =
'char'
```
:::info
In Matlab, character arrays are enclosed in **single** quotes.
:::
#### 2.2. Strings
```matlab
>> s = "Hello, world!";
>> class(s)
ans =
'string'
```
:::info
In Matlab, character arrays are enclosed in **double** quotes.
:::
#### 2.3. Structures
:::info
Related data grouped together is a **struct**.
:::
```matlab
>> person.name = 'Chris Ohhhh';
>> person.age = 18;
>> person.email = "chris@example.com";
>> class(person)
ans =
'struct'
```
#### 2.4. Logical values
```matlab
>> logical_value = true;
>> class(logical_value)
ans =
'logical'
```
:::info
In programming language, **true always represents as 1, while false is 0**.
:::
## **Data structures**
| Data Structures | Description | Example |
|-----------------|--------------------------------------------------------------------|-----------------------------------|
| **Cell arrays** | Containing different data types in each cell, including arrays, matrices, or strings. | `{1, 'apple', [3, 4; 5, 6]}` |
| **Arrays** | A collection of elements of the same data type arranged in a grid. | `[1, 2, 3, 4, 5]` (1D array) |
| **Matrices** | A 2D array of numbers arranged in rows and columns. | `[1, 2; 3, 4]` (2x2 matrix) |
### 1. Cell arrays
```matlab
>> cell_array = {1, 'hello'};
>> class(cell_array)
ans =
'cell'
```
:::info
Cell arrays are enclosed in **curly braces** {}.
:::
### 2. Array and Matrices
**MATLAB** is an abbreviation for **"matrix laboratory."** While other programming languages mostly work with numbers one at a time, MATLAB® is designed to operate primarily on whole matrices and arrays.
All MATLAB variables are multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used for linear algebra.
### Array creation
To create an **array** with four elements in a **single row**, separate the elements with either a comma (,) or a space.
```matlab
>> a = [10 20 30 40] % same as typing a = [10, 20, 30, 40]
a =
10 20 30 40
```
This type of array is a row vector.
### Array indexing
Matlab is a funny language, the indexing starts from 1 instead of 0 (Matlab unlike all other programming languages). **Everything in Matlab starts from 1.**
```matlab
>> a(1)
ans =
10
>> a(end) % In Matlab, "end" means the last one.
ans =
40
```
### Matrix creation
:::info
A **matrix** is a **N-dimensional array** of numbers. To create a matrix that has **multiple rows**, separate the rows with semicolons.
:::
```matlab
>> A = [1 3 5; 2 4 6; 7 8 10]
A =
1 3 5
2 4 6
7 8 10
```
### Matrix indexing
We can reference the element in the **m-th row and n-th column** of the matrix by **A(m, n)**.
```matlab
>> A(1, 3) % Row 1, column 3
>> A(3, 1) % Row 3, column 1
```
Less common, but sometimes useful, is to use a single subscript that **traverses down each column in order**:
```matlab
>> A(3) % Row 3, column 1
>> A(7) % Row 1, column 2
```
To refer to multiple elements of an array, use the colon operator, which allows you to specify a range of the form **start:end**. For example, list the elements in the first three rows and the second column of A:
```matlab
>> A(1:3,2) % You can view this command as A(1,2); A(2,2); A(3,2)
ans =
3
4
8
```
**The colon alone**, without start or end values, **specifies all of the elements in that dimension**. For example, select all the columns in the third row of A:
```matlab
>> A(3,:) % You can view this command as A(3, all) = A(3,1), A(3,2), A(3,3)
ans =
7 8 10
```
:::info
Exercise
What if you'd like to select first column of A matrix?
```matlab
A(?,?)
```
:::
Also, we can initialize matrices faster using:
```matlab
>> a = ones(5, 10)
a =
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
>> b = zeros(3, 7)
b =
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
```
## III. Operations
### 1. Arithmetic Operators
For numbers, we have the unary operators:
| Operator | Description | Example |
|----------|-------------|-----------------|
| `+` | Addition | `5 + 3` results in `8` |
| `-` | Subtraction | `7 - 2` results in `5` |
| `*` | Multiplication | `4 * 6` results in `24` |
| `/` | Division | `8 / 2` results in `4` |
| `.^` | Power | `2 .^ 3` results in `8` |
For example:
```matlab
% The order of the operators follows standard Math
>> a = 5 + 2;
>> b = 5 + 2 * 5;
>> c = 5 + 2 * 5 .^ 2;
```
### 2. Comparison operators
We have operators for the Boolean datatype as well.
| Operator | Meaning | Example | Output |
|----------|--------------------------|-----------|--------|
| == | Equal | 5 == 3 | false |
| ~= | Not equal | 5 ~= 3 | |
| > | Greater than | 10.3 > 2 | |
| < | Less than | 2 < -1 | |
| >= | Greater than or equal to | 5 >= 5 | |
| <= | Less than or equal to | 5 <= 4 | |
```matlab
% Define two variables
>> a = 5;
>> b = 10;
% Compare the two variables and store the result in a Boolean variable
>> c = (a > b);
% Display the result
>> disp(c); % Output: 0 (false)
```
:::success
## Recap Example ##
```matlab=
% Clear previous variables and close all figures
clear
close all
% Numeric operations
x = 3.5;
y = int32(5);
z = x + single(y); % Convert y to single for addition with x
% Matrix creation and indexing
A = [1 2 3; 4 5 6; 7 8 9];
second_col = A(:,2); % Select the second column of matrix A
% Display results
disp('Result of z:'); disp(z)
disp('First column of A:'); disp(first_col)
```
:::
:::info
### Did you know that you can also compare arrays? ###
```
>> a = [1 1 1; 2 2 2];
>> b = [-1 1 1; 2 2 -2];
%Let's try this!
>> a == b
>> a ~= b
```
:::
### 3. Logical operators
| Operator | Meaning | Example | Output |
|----------|---------------------------------------|-------------|--------|
| && | (and) True if both statements are true | 5<9 && 3<5 | true |
| \|\| | (or) True if one of the statements is true | 5<9 \|\| 5>9 | true |
| ~ | (invert) Reverse the result | ~ 5<3 | |
```matlab
% Define two Boolean variables
a = true;
b = false;
class(a)
class(b)
% Logical AND operator (&&)
c = a && b; % false
% Logical OR operator (||)
d = a || b; % true
% Logical NOT operator (~)
e = ~a; % false
```
It's either `true` or `false`. Only two values in this type.
:::info
**Example to try: Can I buy an iPhone16?**
```matlab
iPhone16_price = 29900;
hourly_rate = 100;
monthly_work_hour = 160;
max_monthly_work_hour = 200;
salary = monthly_work_hour * hourly_rate;
disp(salary >= iPhone16_price && monthly_work_hour >= max_month_work_hour)
```
:::
Notice that I use smaller case for variable and use "_" in between words.
* There is no any conventional coding style in Matlab, just be **consistent**.
```matlab
workHour % Some use this
work_hour % I prefer this
```
### 4. Matrix operators
When dealing with matrices, we need to be careful with the operators.
| Operator | Description | Mathematical Notation |
|----------|------------------------------------|----------------------------------------|
| `+` | Element-wise addition | $$ C_{ij} = A_{ij} + B_{ij} $$ |
| `-` | Element-wise subtraction | $$ C_{ij} = A_{ij} - B_{ij} $$ |
| `.*` | Element-wise matrix multiplication | $$ C_{ij} = A_{ij} \cdot B_{ij} $$ |
| `./` | Element-wise matrix division | $$ C_{ij} = \frac{A_{ij}}{B_{ij}} $$ |
| `.^` | Element-wise matrix power | $$ C_{ij} = A_{ij}^{k} $$ |
| `*` | Matrix multiplication | $$ C = A \cdot B $$ |
| `/` | Matrix division (right) | $$ C = B \cdot A^{-1} $$ |
| `'` | Matrix transpose | $$ A^T $$ |
We can mix matrices and numbers operators when it is element-wise.
```matlab
>> A = [1 2; 3 4]
A =
1 2
3 4
>> A + 1
>> A .* 2
>> A .^ 3
>> B = [5 6; 7 8]
B =
5 6
7 8
>> A + B
>> A * B
>> A .* B
```
To transpose a matrix, use a single quote ('):
```matlab
>> A = [1 2; 3 4]
A =
1 2
3 4
>> A'
ans =
1 3
2 4
```
:::info
**Exercise**
Let's calculate the final grade of Student A and Student B who are taking English, Science, and Math classes by using **matrix operations**.
| Student | English | Science | Math |
| ------- | ------- | ------- | ---- |
| A | 80 | 85 | 88 |
| B | 89 | 92 | 91 |
English, Science, and Math class has a weight of 0.3, 0.35, and 0.35, respectively, in the final grade.
:::
## Workspace Variables
The workspace contains variables that you create within or import into MATLAB® from data files or other programs. For example, these statements create variables A and B in the workspace.
```matlab
>> A = 3.5;
>> B = [1 0 0; 0 1 0; 0 0 1];
```
You can view the contents of the workspace using `whos`.
```matlab
>> whos
Name Size Bytes Class Attributes
A 1x1 8 double
B 3x3 72 double
```
In MATLAB, **the `double` data type is an 8-byte (64-bit)** floating-point number representation. This means that a variable of type double uses 8 bytes of memory to store the value.
Workspace variables do not persist after you exit MATLAB. Save your data for later use with the save command:
```matlab
>> save myfile.mat
```
To clear all the variables from the workspace, use the `clear` command.
Restore data from a MAT-file into the workspace using load:
```matlab
>> load myfile.mat
```