Basic MATLAB Programming Course
Basic MATLAB Programming Course
Basic MATLAB Programming Course
Programming Course
What we will learn in this session
Summary
• help command Online help
• lookfor keyword Lists related commands
• which Version and location info
• clear Clears the workspace
• clc Clears the command window
• diary filename Sends output to file
• diary on/off Turns diary on/off
• who, whos Lists content of the workspace
• more on/off Enables/disables paged output
• Ctrl+c Aborts operation
• … Continuation
• % Comments
Basic Commands
MATLAB BASICS
Variables and Arrays
Array: A collection of data values organized into
rows and columns, and known by a single name.
Row 1
Row 2
Row 3
arr(3,2)
Row 4
1
c= 3 3x1 array 3 elements, column vector
5
Row # Column #
Declaring Single Variables
To declare single variables, type in a
variable name and type in its value.
MATLAB will decide on the data type
automatically, so you don’t have to declare
its data type.
Example:
var1 = 3;
thisIsAVariable = 56;
Declaring Single Variables
Variables cannot have numbers or
symbols in front of them.
Example of illegal variable names:
1var
#aaa
Special Values/Variables
• pi: value up to 15 significant digits
• i, j: sqrt(-1)
• Inf: infinity (such as division by 0)
• NaN: Not-a-Number (division of zero by zero)
• clock: current date and time in the form of a 6-element
row vector containing the year, month, day, hour,
minute, and second
• date: current date as a string such as 16-Feb-2004
• eps: epsilon is the smallest difference between two
numbers
• ans: stores the result of an expression
Vectors
Some useful commands:
y = x’ transpose of vector x
dot (x, y) returns the scalar dot product of the vector x and y.
Examples-Vectors
Real Scalars
>> x = 5
x=5
Row Vector (1 x 3)
>> x = [ 1 2 3 ]
x=
1 2 3
Column Vector ( 3 x 1)
>> x = [ 1 ; 2 ; 3 ]; %”;” suppresses output
>> x
x=
1
2
3
Note: Variable Names are case sensitive
Matrix Variables
Matrix variables are initialized similar to
single variables.
The values in a matrix variable is defined
in square brackets.
Example:
aaa = [1,2,3,4];
bbb = [1;2;3;4];
Row Matrix
To create a row matrix, use the comma to
separate the values.
Example:
rowMatrix = [1,2,3,4,5];
Example
•Rows and columns are always numbered starting at 1
A = [2 7 4] 2 7 4
A = [2; 7; 4] 7
2 7 4
A = [2 7 4; 3 8 9] 3 8 9
2 7 4 2 7 4
B=[AA] ? 3 8 9 3 8 9
Try It Yourself
Create this matrix:
1 2
A
3 4
Try It Yourself
Create this matrix:
2 4 5
matrixB 2 4 5
5 3 5
Accessing Matrix Values
To access a specific value inside a matrix,
use this command:
matrixName(rowNumber, colNumber)
Example: to access a value inside row 3
and column 2.
matrixName(3,2)
Try It Yourself
Create this matrix:
3 4 5
matrixB 8 9 10
6 7 1
>> x = A ( 1, 3 ) %A(<row>,<column>)
x=
3
3 4 5
matrixB 8 9 10
6 7 1
Get all the values from row 3 and save it into a new
variable.
Get all the values from column 1 and save it into a new
variable.
Creating a Matrix of Zeros
To create a matrix of zeros, use the zeros
command.
Example: create a 6 X 5 matrix of zeros.
zeros(6,5)
Example
Creating a Matrix of Ones
To create a matrix of ones, use the ones
command.
Example: create a 5 X 3 matrix of ones.
ones(5,3)
Example
Creating a Matrix of Random
Numbers
To create a matrix of random numbers,
use the rand command.
Example: create a 4 X 4 matrix of random
numbers.
rand(4,4)
Example
>> B = [ 1 2 ; 8 9 ]
ans =
1 2
8 9
>> t = [ 0 : 0.01 : 10 ];
>> x = sin ( 2 * pi * t );
>> sum ( A )
ans =
12 15 18
>> diag(A)
ans =
1
5
9
At a glance……..
• Initializing with Built-in Functions
89
Sorting Matrices
To sort a matrix, use the sort command.
Example: sort matrix A in ascending order.
B = sort(A,’ascend/descend’)
Default is ascending mode.
Example: Sorting a Row Matrix
Example: Sorting a Column Matrix
Example: Sorting a Regular Matrix
Example: Sorting a Row Matrix in
Descend Mode
Flipping a Matrix
A matrix can be flipped using the flipud or
fliplr commands.
Command flipud flips the matrix in
UP/DOWN direction.
Command fliplr flips the matrix in
LEFT/RIGHT direction.
Example: flipud
Example: fliplr
Term by Term vs Matrix Operations
>> B = [ 1 2 ; 3 4 ] ;
B=
1 2
3 4
.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
Initializing with Keyboard Input
Data files
• save filename var1 var2 …
>> save myfile.mat x y
binary
>> save myfile.dat x –ascii ascii
• load filename
>> load myfile.mat binary
>> load myfile.dat –ascii ascii
Loading & saving Excel files
% Create an Excel file named myExample.xlsx.
filename = 'myExample.xlsx';
A = xlsread(filename)
Built-in MATLAB Functions
• result = function_name( input );
– abs, sign
– log, log10, log2
– Exp
– sqrt, std
– sin, cos, tan
– asin, acos, atan
– max, min
– mean, median, mode
– round, floor, ceil, fix
– mod, rem
• help elfun help for elementary math functions
Passing a vector to a function like sum, mean, std
will calculate the property within the vector
>> sum([1,2,3,4,5])
= 15
>> mean([1,2,3,4,5])
=3
Cell
C = cell(2,2); % create a 2 by 2 cell
X=
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
Some important built-in functions
meshgrid -
[X,Y] = meshgrid(1:3,10:14)
X= Y=
1 2 3 10 10 10
1 2 3
11 11 11
1 2 3
12 12 12
1 2 3
1 2 3 13 13 13
14 14 14
Repmat -Repeat copies of array
A= B=
aaa = rand(1,100);
bbb = 1:1:100
color = 1;
if (color == 1)
% if block
figure, plot(bbb,aaa,':r');
else
% else block
figure, plot(bbb,aaa,'b');
end
Example
clear, close all
clc
x = 3;
if (x > 5)
disp('The number is more than 5.')
elseif (x == 5)
disp('The number is equal to 5.')
else
disp('The number is less than 5.')
end
For loop
Used to repeat a set of statements
multiple times.
The for loop format is:
for(startingvalue:increment:endingvalue)
For Loop
end
Example: Display value inside for
loop
clear, close all
clc
for i = 1:1:15
st1 = strcat('The value of i inside the
loop is: ',int2str(i));
disp(st1)
end
Example: Display “Hello World” 10
Times
st1 = 'Hello World!';
for i = 1:1:10
disp(st1)
end
Example: Check Value Inside
Matrix
clear, close all
clc
for i = 1:1:row
for j = 1:1:col
currNo = matA(i,j);
st1 = strcat('The value being tested is: ', num2str(currNo),'.');
disp(st1)
if (currNo > 3)
disp('The current value is larger than 3.')
else
disp('The current value is less or equal than 3.')
end
end
end
While loop
Used to repeat a set of statements while
the tested condition is true.
The while loop format is:
while(condition)
The tested condition is the same as if…
else
Conditions that can be tested
% conditions that can be tested
% == : is equal to
% ~= : is not equal to
% > : larger than
% >= : larger than or equal
% <= : less than or equal
% < : less than
Example: Display value inside for
loop
clear, close all
clc
counter = 1;
number1 = 4;
number2 = 5;
selection = 1;
if selection == 1
hasil = addFcn(number1,number2);
elseif selection == 2
hasil = subFcn(number1,number2);
elseif selection == 3
hasil = mulFcn(number1,number2);
elseif selection == 4
hasil = divFcn(number1,number2);
else
disp('The selection is invalid.')
end
function called
calcSphereVolume.
The formula for volume
3
is:
Problem 2
Write a program that plots the function:
y x x 3x 6
3 2
>>x=linspace(0,4*pi,100);
0.8
0.6
>>y=sin(x); 0.4
0.2
-0.4
-0.6
>>plot(y) -0.8
-1
0 10 20 30 40 50 60 70 80 90 100
Plot the function e-x/3sin(x) between
0≤x≤4π
Create an x-array of 100 samples between
0 and 4π.
>>x=linspace(0,4*pi,100);
0.6
0.5
0.4
>>plot(y2) 0.3
0.2
0.1
-0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
Additional References:
http://web.mit.edu/6.003/www/matlab.html
http://web.mit.edu/6.003/www/Labs/matlab
_6003.pdf
http://web.mit.edu/6.003/www/Labs/matlab
_tut.pdf
The End