Sie sind auf Seite 1von 31

MATLAB PRIMER

Energy Engineering Class College of Engineering UP Diliman

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

Matlab Interface

Editor

Workspace

Current Directory

Command History Command Window

Matlab Interface
Current Directory show the working directory and files

inside the directory Editor - text-editor where a user can create Matlab (*.m) m-files Command Window where a user can issue and call matlab commands at the prompt Workspace shows the current variables and data loaded into the matlab memory Command History shows a list of previously called or issued commands

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]

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

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 (B C) To transpose matrices, use a quote ( ) Try it! Make Matrix A a column vector

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

Matrix Operations
Element-wise multipication

( .* ) dot-asterisk operation
Example
B .*

B
1 16 49 4 9 25 36 64 81

Raising Matrix to n-th power (element-wise): B .^ n


B .^ 3 1 8 27 64 125 216 343 512 729

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)

Matrix Operation
Concatenation [B, B]

1 4 7

2 5 8

3 6 9

1 4 7

2 5 8

3 6 9

To concatenate vertically, use semicolon instead of coma [B; B]


1 4 7 1 4 7

2 5 8 2 5 8

3 6 9 3 6 9

Array Indexing
Used to select a part of an array, whether a smaller matrix or a

column/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

Array Indexing
Try it! Select and display only the 3rd row Select and display the 3rd and 4th column Select and display the smaller matrix in the 4th quadrant

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

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)
Importdata more general and flexible compared to csvread
Need not be comma-separated Delimeter character that separates the data (space or comma) Number_header_lines which row data actually starts

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

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

Display imported Data


Variable Editor Window

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

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)

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

Control Flow
ELSE, ELSEIF a = randi(100, 1); if a < 30
disp('small')

elseif a < 80
disp('medium')

else
disp('large')

end

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: )

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

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

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 mfile. It skips counting when a line in the file is not considered a code (either a comment/ %, invalid character or is a whitespace)

Control Flow
Break Enables early exit in a loop execution Code below is similar to the While-Loop but break was utilized

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

Using (and creating) Functions


Matlab has lots and lots of functions!

You too can create your own

Format:

function output = function_name(input) output = do_operations_on_(input) end


Save your file with the *.m extension

Using (and creating) Functions


Try it! Implement the factorial (!) as matlab code. Definition: n! = n * (n-1)! 0! = 1

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

Das könnte Ihnen auch gefallen