matlab primer 2321231
TRANSCRIPT
-
8/13/2019 Matlab Primer 2321231
1/31
MATLAB PRIMER
Energy Engineering Class
College of Engineering
UP Diliman
-
8/13/2019 Matlab Primer 2321231
2/31
Matlab Introduction
MAT(rix) LAB(oratory)
a high-level technical computing language and interactive
environment for algorithm development, data
visualization, data analysis, and numeric computation
-
8/13/2019 Matlab Primer 2321231
3/31
Matlab Interface
Editor Workspace
Command
History
Current
Directory
Command Window
-
8/13/2019 Matlab Primer 2321231
4/31
Matlab Interface
Current Directoryshow the working directory and files
inside the directory
Editor - text-editor where a user can create Matlab (*.m)
m-files
Command Windowwhere a user can issue and call
matlab commands at the prompt
Workspaceshows the current variables and data loaded
into the matlab memory
Command Historyshows a list of previously called or
issued commands
-
8/13/2019 Matlab Primer 2321231
5/31
Creating Variables
Matlab variables can accept any data at creation
No need to declare data type
Example (try it!)
A = 1 B = Hello World
C = [0 1 2 3]
To suppress displaying of data, use semi-colon ( ; ) A = 1;
B = Hello World!
C = [0 1 2 3]
-
8/13/2019 Matlab Primer 2321231
6/31
Creating Matrices
1-dimensional matrix (row vector)
A = [1 2 3 4 5]
Use semicolon to separate data to rows B = [1 2 3; 4 5 6; 7 8 9]
Other special matrices
ones(m,n)
Zeros(m, n)
Rand(m, n)
m = number of rows
n = number of columns
-
8/13/2019 Matlab Primer 2321231
7/31
Matrix Operations
Try it! : Create a 3x3 Matrix C of ones!
Adding matrices B + C
Ans:
2 3 4
5 6 7
8 9 10
TIP: Make sure B and C has the same size
Details the same with subtracting matrices (BC)
To transpose matrices, use a quote ( ) Try it! Make Matrix A a column vector
-
8/13/2019 Matlab Primer 2321231
8/31
Matrix Operations
Matrix Multiplication
Inner products between row and columns
( * )operator
Example
B * B
30 36 42
66 81 96
102 126 150
B * inv(B) inv(B) gets the inverse of the matrix
2 0 2
8 0 0
16 0 8
-
8/13/2019 Matlab Primer 2321231
9/31
Matrix Operations
Element-wise multipication
( .* )dot-asterisk operation
Example
B .* B
1 4 9 16 25 36
49 64 81
Raising Matrix to n-th power (element-wise): B .^ n
B .^ 3 1 8 27
64 125 216
343 512 729
-
8/13/2019 Matlab Primer 2321231
10/31
Matrix Operations
Matrix Division
( / ) or matrix right division: B / A = B * inv(A)
( \ ) or matrix left division: A \ B = inv(A) * B
( ./ ) or array right division: A./B = A/B (element-wise)
( .\ ) or array left division: A.\B = B/A (element-wise)
-
8/13/2019 Matlab Primer 2321231
11/31
Matrix Operation
Concatenation [B, B]
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
To concatenate vertically, use semicolon instead of coma [B; B]
1 2 3
4 5 6 7 8 9
1 2 3
4 5 6
7 8 9
-
8/13/2019 Matlab Primer 2321231
12/31
Array Indexing
Used to select a part of an array, whether a smaller matrix or acolumn/row vector
A = magic(4) 16 2 3 13
5 11 10 8 9 7 6 12
4 14 15 1
A(4, 2) = ?
A (8) = ?A(1:3, 2) =
2
11
7
-
8/13/2019 Matlab Primer 2321231
13/31
Array Indexing
Try it!
Select and display only the 3rdrow
Select and display the 3rdand 4thcolumn
Select and display the smaller matrix in the 4thquadrant
-
8/13/2019 Matlab Primer 2321231
14/31
Common Matlab functions
Sum
Computes the sum of each column
Try it!
Compute the sum of columns of B
Compute the sum of rows of B
Reshape: Reshapes the matrix into desired new number
of rows and columns
Repmat: Replicates and tiles the input array Str2num / Num2str : converts strings to numbers /vice
versa, respectively
Useful when copying numerical data from external sources
-
8/13/2019 Matlab Primer 2321231
15/31
Importing Data from CSV
To import data from a comma-separated value (CSV)
formatted files, we can use the following functions
M = csvread(filename)
filename- is the name of the CSV file and all data will be read into
variable M
NOTE: data should not have header names (else, error would occur)
M = importdata(filename, delimeter, number_header_lines)
Importdatamore general and flexible compared to csvread
Need not be comma-separated
Delimetercharacter that separates the data (space or comma)
Number_header_lineswhich row data actually starts
-
8/13/2019 Matlab Primer 2321231
16/31
Importing Data from CSV
M = clipboard(pastespecial)
User can open the CSV using a spreadsheet program (MS Excel or
Open/LibreOffice Calc) and copy the data to memory
clipboard will paste these data into Matlab workspace
Data would be separated to texts and numbers
-
8/13/2019 Matlab Primer 2321231
17/31
Display imported data
There are at least 2 ways:
Type the variable name in the Command Window
Would print the values (could be verbose) Double click the variable name in the Workspace window
Variable editor window would open
Variable editor windows shares same space with Editor Window
-
8/13/2019 Matlab Primer 2321231
18/31
Display imported Data
Variable Editor Window
-
8/13/2019 Matlab Primer 2321231
19/31
Plotting Data
To visualize your data, we can use plots
Given a vector of values y, call
plot(y)
The x-axis would be the index of the value
If you have values for the x-axis, call
plot(x,y)
Lets try plotting data!
X = 1:10 Y = rand(10,1) * 10;
Plot the data
-
8/13/2019 Matlab Primer 2321231
20/31
Plotting Data
3-dimensional data For plotting 3-dimensional data, we can use the following
Z = peaks; % lets create 2-dimensional dummy data
surf (To create surface graphs ) surf(Z) surf(X, Y, Z) (if you have value for the X- and Y-axis)
Contour contour(Z)
contour(X, Y, Z) (if you have value for the X- and Y-axis)
surfc (create surface plot and contour plot at the bottom) surfc(Z)
surf(X, Y, Z) (if you have value for the X- and Y-axis)
mesh (similar to surf but retains only the wireframe) mesh(Z)
mesh(X, Y, Z) (if you have value for the X- and Y-axis)
-
8/13/2019 Matlab Primer 2321231
21/31
Control Flow
Control flows are important to direct the execution of your
code depending on the values of your variables
IF, ELSE a = randi(100, 1); % Generate a random number
if rem(a, 2) == 0 % If it is even, divide by 2
disp('a is even')
b = a/2;
else disp('a is odd)
end
-
8/13/2019 Matlab Primer 2321231
22/31
Control Flow
ELSE, ELSEIF
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80 disp('medium')
else
disp('large')
end
-
8/13/2019 Matlab Primer 2321231
23/31
Control Flow
SWITCH
NOTE: For both IF and SWITCH, once the code enters and executes a
section by satisfying an IF or a CASE, the program exits the code block
Lets Try! Create code by typing a number and telling the user if its a
negative number, a positive number or zero. a = input(Type number: )
-
8/13/2019 Matlab Primer 2321231
24/31
Control Flow
For Loop
Runs a part of the code in a predetermined number of time
H = rand(10);
[m, n] = size(H);
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end end
-
8/13/2019 Matlab Primer 2321231
25/31
Control Flow
While Loop
Runs the code until a certain condition is met
Code to find the zero of f(x) = x3-2x -5 between 0 and 3
-
8/13/2019 Matlab Primer 2321231
26/31
Control Flow
Continue
Goes to the next iteration of the Loop, skipping all the commands
after it
Code below counts the number of command lines in a Matlab m-
file. It skips counting when a line in the file is not considered a code(either a comment/ %, invalid character or is a whitespace)
-
8/13/2019 Matlab Primer 2321231
27/31
Control Flow
Break
Enables early exit in a loop execution
Code below is similar to the While-Loop but break was utilized
-
8/13/2019 Matlab Primer 2321231
28/31
Control Flow
Return
Break the flow of the program and gives back the control to the
main function, will skip all the succeeding parts of the code.
Usually found at the end of a function to return control to the
invoking function Can also be inserted in middle part of the code to cause premature
exit of execution
-
8/13/2019 Matlab Primer 2321231
29/31
Using (and creating) Functions
Matlab has lots and lots of functions!
You too can create your own
Format:
functionoutput = function_name(input)
output = do_operations_on_(input)
end
Save your file with the *.m extension
-
8/13/2019 Matlab Primer 2321231
30/31
Using (and creating) Functions
Try it!
Implement the factorial (!) as matlab code.
Definition: n! = n * (n-1)!
0! = 1
-
8/13/2019 Matlab Primer 2321231
31/31
Resources
Matlab Primer (www.mathworks.com)
Google is your bestfriend
Matlab File Exchange
Lots of community developed code and software
Forums on Matlab problems and tips
http://www.mathworks.com/http://www.mathworks.com/