## 10X Your Productivity: Grab Your Free Online Course Right Now! |

In this article, you’ll learn the basics of MATLAB Programming in 5 minutes, including how to:

- Create variables, vectors, and matrices
- Use MATLAB functions and scripts
- Create loops and conditions
- Read and write text and Excel files

## Creating Variables, Vectors, and Matrices

### How to Define a Variable in MATLAB

To define a variable, write the name of the variable followed by “=” and the value of the variable:

numberVariable = 5; % variable containing a number stringVariable = 'string'; % variable containing a string

- The “;” is used to prevent MATLAB from displaying the value of your variable in your workspace when you define it.
- The “%” is used to add a comment to your code.

Furthermore, MATLAB remembers what you wrote. If you want to access a command that you wrote earlier in your workspace, use the up arrow key to get your previous command.

### How to Create a Vector in MATLAB

In MATLAB, you can create row vectors and column vectors:

**Row vector:**create a vector in MATLAB by putting numbers (or strings) next to each other and enclosing them with square brackets:vector = [1 2 3 4 5]; % row vector stringVector = [{'speed'} {'size'}]; % string row vector

This defines the following vectors:

\(vector=\begin{pmatrix}1 &2 &3&4 &5\end{pmatrix}~~~~~~~~~~~~~~~~~~stringVector=\begin{pmatrix}\{‘speed’\}& \{‘size’\}\end{pmatrix}\)

**Column vector:**use a single quotation mark to define a column vector:vector = [1 2 3 4 5]'; % column vector stringVector = [{'speed'} {'size'}]'; % string column vector

\(vector=\begin{pmatrix}1 \\2 \\3\\4 \\5\end{pmatrix}~~~~~~~~~~~~~~~~~~stringVector=\begin{pmatrix}\{‘speed’\}\\\{‘size’\}\end{pmatrix}\)

As you can see, you need to use braces to separate strings in a vector; otherwise, MATLAB tries to concatenate them.

If you want to learn all the technical stuff on vectors, see MATLAB Vector Tutorial: Create, Add, Concatenate, and Extract

### How to Create a Matrix in MATLAB

You can create a matrix in MATLAB by writing numbers or strings next to each other to define the rows and using a semicolon to go to the next row:

matrix = [1 2 3 ; 4 5 6 ; 7 8 9]; stringMatrix = [{'position'} {'speed'} ; {'size'} {'acceleration'}];

The result is the following matrices:

\(matrix=\begin{pmatrix}1 &2 &3\\4 &5 &6 \\7 &8 &9\end{pmatrix}~~~~~~~~~~~~~~~~~~stringMatrix=\begin{pmatrix}\{‘position’\}& \{‘speed’\}\\\{‘size’\} & \{‘acceleration’\}\end{pmatrix}\)

You can then multiply matrices as the following:

` A*B % classic matrix multiplication in MATLAB`

If you want to learn more about matrices, see MATLAB Matrix: Create, Transpose, Extract, Multiply Matrices

## MATLAB: Function and Script

### Writing a Script

To write a new MATLAB script, follow these steps:

- Go to the top left of your MATLAB windows, under the “
**HOME**” tab - Click on “
**New Script**“:

- Save your script by using the keyword shortcut “
**CTRL+S**” or by clicking “**Save**” at the top left of the MATLAB editor:

### Defining a MATLAB Function

Here’s the syntax to define a MATLAB function:

function [out1, out2, out3] = functionName(in1, in2) Instructions end

**Outputs**: list every output of your function separated with commas in between square brackets.**Inputs:**list input separated by commas and enclosed by parenthesis.

If you want to know all the nitty-gritty details of MATLAB functions, see MATLAB Function: Vector, Matrix, Or Single Input/Output Functions.

## Creating Loops and Conditions

### MATLAB for Loop

You can define a for loop in MATLAB as the following:

for i = 1:n % n is the number of loops you want Instructions; % what you want to do n times end

For example, here’s how to create a for loop that counts to 10:

for i = 1:10 i end

To see more examples of for loops, see MATLAB For Loop: Example of Simple, Backward, and Nested For Loops.

### While Loop

If you want to define the while loop in MATLAB, you can use the following syntax:

while condition Instructions end

For example, here’s how to create a wide loop that counts to 10:

i = 10; while i~=10 % while i is not equal to 10 i=i+1 end

### If Else MATLAB

The basic if else MATLAB structure is:

if firstCondition firstInstruction elseif secondCondition secondInstruction else otherInstructions end

For example, if your condition is “A is not equal to B,” you’d have:

**A and B matrices:**if ~isequal(A, B) instruction end

**A and B numbers:**if A~=B instruction end

If you want to learn more complicated examples such as switch case structures, A less than or equal to B, or strings and logical operators, see If Else MATLAB: Conditional Statements if A Is Not Equal to B.

## MATLAB: Reading and Writing Files

### Text Files

- To read a text file, you need to open it with the
**fopen**MATLAB command, read it using a while loop, and close it using the**fclose**MATLAB command:

fid = fopen(fileName); while ~feof(fid) textLineEntry = fgetl(fid); end fclose(fid);

To learn more about how to read a text file in MATLAB, see MATLAB: Read a Text File Line By Line Using fgetl.

- Using the same structure, we can employ the
**fprintf**MATLAB command to write a new text file. For example, here’s how to write the word “Text” in a new text file named “textFileName.txt”:

fid = fopen('textFileName.txt', 'at'); fprintf(fid, 'Text'); fclose(fid);

To learn more about the

**fprintf**MATLAB command, see fprintf in MATLAB: Text, Matrix, and Complex Number.

### Excel Files

**Reading an Excel file:**an easy way to read an Excel file is to use the**xlsread**MATLAB command. Here’s the basic syntax for that command:

[numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber);

If you want more explanations and examples of how to use this function, see Xlsread Tutorial: Extract Data from Excel in MATLAB.

**Writing into an Excel file:**to write into an Excel file, use the following:

xlswrite(fileName, data, sheetNumber);

For example, if you want to write the following matrix into an Excel file:

\(\begin{pmatrix} \{‘firstWord’\}&\{‘secondWord’\}\\\{‘thirdWord’\} &\{‘fouthWord’\} \end{pmatrix}\)

You can do the following:

variable1 = 'firstWord'; variable2 = 'secondWord'; variable3 = 'thirdWord'; variable4 = 'fourthWord'; data = [{variable1} {variable2} ; {variable3} {variable4}]; fileName = 'excelFile.xlsx'; sheetNumber = 1; xlswrite(fileName, data, sheetNumber);