This document provides an overview of MATLAB, including:
- MATLAB is a software package for numerical computation, originally designed for linear algebra problems using matrices. It has since expanded to include other scientific computations.
- MATLAB treats all variables as matrices and supports various matrix operations like addition, multiplication, element-wise operations, and matrix manipulation functions.
- MATLAB allows plotting of 2D and 3D graphics, importing/exporting of data from files and Excel, and includes flow control statements like if/else, for loops, and while loops to structure code execution.
- Efficient MATLAB programming involves using built-in functions instead of custom functions, preallocating arrays, and avoiding nested loops where possible through matrix operations.
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
Notes for Scilab Programming. This notes includes the mathematics used behind scilab numerical programming. Illustrated with suitable graphics and examples. Each function is explained well with complete example. Helpful to beginners. GUI programming is also explained.
MATLAB's anonymous functions provide an easy way to specify a function. An anonymous function is a function defined without using a separate function file. It is a MATLAB feature that lets you define a mathematical expression of one or more inputs and either assign that expression to a function. This method is good for relatively simple functions that will not be used that often and that can be written in a single expression.
The inline command lets you create a function of any number of variables by giving a string containing the function followed by a series of strings denoting the order of the input variables. It is similar to an Anonymous Function
Previous post we discussed what is a user defined function in MATLAB. This lecture we will discuss how to define a function and how to call the function in a script.
Components of a function is discussed in the previous lecture. The first statement in a function must be function definition.The basic syntax of a function definition is:
function[a, b, c]= basicmath(x,y)
Basically a function accepts an input vector, perform the operation, and returns a result. The sample function given has two input variables and three output variables. But we can also have functions without input or/and output.
In this lecture we will discuss about another flow control method – Loop control.
A loop control is used to execute a set of commands repeatedly
The set of commands is called the body of the loop
MATLAB has two loop control techniques
Counted loops - executes commands a specified number of times
Conditional loops - executes commands as long as a specified expression is true
User-defined functions are similar to the MATLAB pre-defined functions. A function is a MATLAB program that can accept inputs and produce outputs. A function can be called or executed by another program or function.
Code for a function is done in an Editor window or any text editor same way as script and saved as m-file. The m-file must have the same name as the function.
A MATLAB function that accepts another function as an input is called a function function. Function handles are used for passing functions to function functions. Syntax for function function is same as simple functions, but one or more input arguments will be function handles.
Multiple functions within one function file is called local function. Name of function file should be name of main function. Main function can be called from the command window or any other function. Local functions are typed in any order after the main function. Local functions are only visible to other functions in the same file.
A private function is a function residing in a sub directory with the name private. Private functions are visible only to functions in the parent directory.
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
Notes for Scilab Programming. This notes includes the mathematics used behind scilab numerical programming. Illustrated with suitable graphics and examples. Each function is explained well with complete example. Helpful to beginners. GUI programming is also explained.
MATLAB's anonymous functions provide an easy way to specify a function. An anonymous function is a function defined without using a separate function file. It is a MATLAB feature that lets you define a mathematical expression of one or more inputs and either assign that expression to a function. This method is good for relatively simple functions that will not be used that often and that can be written in a single expression.
The inline command lets you create a function of any number of variables by giving a string containing the function followed by a series of strings denoting the order of the input variables. It is similar to an Anonymous Function
Previous post we discussed what is a user defined function in MATLAB. This lecture we will discuss how to define a function and how to call the function in a script.
Components of a function is discussed in the previous lecture. The first statement in a function must be function definition.The basic syntax of a function definition is:
function[a, b, c]= basicmath(x,y)
Basically a function accepts an input vector, perform the operation, and returns a result. The sample function given has two input variables and three output variables. But we can also have functions without input or/and output.
In this lecture we will discuss about another flow control method – Loop control.
A loop control is used to execute a set of commands repeatedly
The set of commands is called the body of the loop
MATLAB has two loop control techniques
Counted loops - executes commands a specified number of times
Conditional loops - executes commands as long as a specified expression is true
User-defined functions are similar to the MATLAB pre-defined functions. A function is a MATLAB program that can accept inputs and produce outputs. A function can be called or executed by another program or function.
Code for a function is done in an Editor window or any text editor same way as script and saved as m-file. The m-file must have the same name as the function.
A MATLAB function that accepts another function as an input is called a function function. Function handles are used for passing functions to function functions. Syntax for function function is same as simple functions, but one or more input arguments will be function handles.
Multiple functions within one function file is called local function. Name of function file should be name of main function. Main function can be called from the command window or any other function. Local functions are typed in any order after the main function. Local functions are only visible to other functions in the same file.
A private function is a function residing in a sub directory with the name private. Private functions are visible only to functions in the parent directory.
Polynomials are very important mathematical tool for Engineers. In this lecture we will discuss about how to deal with Polynomials in MATLAB and one of its application, Curve Fitting.
The name MATLAB stands for MATrix LABoratory.MATLAB is a high-performance language for technical computing.
It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a modern programming language environment: it has sophisticated data structures, contains built-in editing and debugging tools, and supports object-oriented programming.
These factor make MATLAB an excellent tool for teaching and research.
More instructions for the lab write-up1) You are not obli.docxgilpinleeanna
More instructions for the lab write-up:
1) You are not obligated to use the 'diary' function. It was presented only for you convenience. You
should be copying and pasting your code, plots, and results into some sort of "Word" type editor that
will allow you to import graphs and such. Make sure you always include the commands to generate
what is been asked and include the outputs (from command window and plots), unless the problem
says to suppress it.
2) Edit this document: there should be no code or MATLAB commands that do not pertain to the
exercises you are presenting in your final submission. For each exercise, only the relevant code that
performs the task should be included. Do not include error messages. So once you have determined
either the command line instructions or the appropriate script file that will perform the task you are
given for the exercise, you should only include that and the associated output. Copy/paste these into
your final submission document followed by the output (including plots) that these MATLAB
instructions generate.
3) All code, output and plots for an exercise are to be grouped together. Do not put them in appendix, at
the end of the writeup, etc. In particular, put any mfiles you write BEFORE you first call them.
Each exercise, as well as the part of the exercises, is to be clearly demarked. Do not blend them all
together into some sort of composition style paper, complimentary to this: do NOT double space.
You can have spacing that makes your lab report look nice, but do not double space sections of text
as you would in a literature paper.
4) You can suppress much of the MATLAB output. If you need to create a vector, "x = 0:0.1:10" for
example, for use, there is no need to include this as output in your writeup. Just make sure you
include whatever result you are asked to show. Plots also do not have to be a full, or even half page.
They just have to be large enough that the relevant structure can be seen.
5) Before you put down any code, plots, etc. answer whatever questions that the exercise asks first.
You will follow this with the results of your work that support your answer.
SAMPLE QUESTION:
Exercise 1: Consider the function
f (x,C)=
sin(C x)
Cx
(a) Create a vector x with 100 elements from -3*pi to 3*pi. Write f as an inline or anonymous function
and generate the vectors y1 = f(x,C1), y2 = f(x,C2) and y3 = f(x,C3), where C1 = 1, C2 = 2 and
C3 = 3. Make sure you suppress the output of x and y's vectors. Plot the function f (for the three
C's above), name the axis, give a title to the plot and include a legend to identify the plots. Add a
grid to the plot.
(b) Without using inline or anonymous functions write a function+function structure m-file that does
the same job as in part (a)
SAMPLE LAB WRITEUP:
MAT 275 MATLAB LAB 1 NAME: ...
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxagnesdcarey33086
SAMPLE QUESTION:
Exercise 1: Consider the function
f (x,C)=
sin(C x)
Cx
(a) Create a vector x with 100 elements from -3*pi to 3*pi. Write f as an inline or anonymous function
and generate the vectors y1 = f(x,C1), y2 = f(x,C2) and y3 = f(x,C3), where C1 = 1, C2 = 2 and
C3 = 3. Make sure you suppress the output of x and y's vectors. Plot the function f (for the three
C's above), name the axis, give a title to the plot and include a legend to identify the plots. Add a
grid to the plot.
(b) Without using inline or anonymous functions write a function+function structure m-file that does
the same job as in part (a)
SAMPLE LAB WRITEUP:
MAT 275 MATLAB LAB 1 NAME: __________________________
LAB DAY and TIME:______________
Instructor: _______________________
Exercise 1
(a)
x = linspace(-3*pi,3*pi); % generating x vector - default value for number
% of pts linspace is 100
f= @(x,C) sin(C*x)./(C*x) % C will be just a constant, no need for ".*"
C1 = 1, C2 = 2, C3 = 3 % Using commans to separate commands
y1 = f(x,C1); y2 = f(x,C2); y3 = f(x,C3); % supressing the y's
plot(x,y1,'b.-', x,y2,'ro-', x,y3,'ks-') % using different markers for
% black and white plots
xlabel('x'), ylabel('y') % labeling the axis
title('f(x,C) = sin(Cx)/(Cx)') % adding a title
legend('C = 1','C = 2','C = 3') % adding a legend
grid on
Command window output:
f =
@(x,C)sin(C*x)./(C*x)
C1 =
1
C2 =
2
C3 =
3
(b)
M-file of structure function+function
function ex1
x = linspace(-3*pi,3*pi); % generating x vector - default value for number
% of pts linspace is 100
C1 = 1, C2 = 2, C3 = 3 % Using commans to separate commands
y1 = f(x,C1); y2 = f(x,C2); y3 = f(x,C3); % function f is defined below
plot(x,y1,'b.-', x,y2,'ro-', x,y3,'ks-') % using different markers for
% black and white plots
xlabel('x'), ylabel('y') % labeling the axis
title('f(x,C) = sin(Cx)/(Cx)') % adding a title
legend('C = 1','C = 2','C = 3') % adding a legend
grid on
end
function y = f(x,C)
y = sin(C*x)./(C*x);
end
Command window output:
C1 =
1
C2 =
2
C3 =
3
Joe Bob
Mon lab: 4:30-6:50
Lab 3
Exercise 1
(a) Create function M-file for banded LU factorization
function [L,U] = luband(A,p)
% LUBAND Banded LU factorization
% Adaptation to LUFACT
% Input:
% A diagonally dominant square matrix
% Output:
% L,U unit lower triangular and upper triangular such that LU=A
n = length(A);
L = eye(n); % ones on diagonal
% Gaussian Elimination
for j = 1:n-1
a = min(j+p.
2. MATLAB
MATLAB is a software package for doing numerical
computation. It was originally designed for solving linear
algebra type problems using matrices. It’s name is derived
from MATrix LABoratory.
MATLAB has since been expanded and now has built-in
functions for solving problems requiring data analysis, signal
processing, optimization, and several other types of scientific
computations. It also contains functions for 2-D and 3-D
graphics and animation.
3. MATLAB Variable names
Variable names are case sensitive.
Variable names can contain up to 63 characters ( as of
MATLAB 6.5 and newer).
Variable names must start with a letter and can be followed by
letters, digits and underscores.
Examples :
>> x = 2;
>> abc_123 = 0.005;
>> 1ab = 2;
Error: Unexpected MATLAB expression
4. MATLAB Special Variables
pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number
5. MATLAB Relational operators
MATLAB supports six relational operators.
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~= (NOT != like in C)
6. MATLAB Logical Operators
MATLAB supports three logical operators.
not ~ % highest precedence
and & % equal precedence with or
or | % equal precedence with and
8. MATLAB Matrices
MATLAB treats all variables as matrices. For our purposes a
matrix can be thought of as an array, in fact, that is how it is
stored.
Vectors are special forms of matrices and contain only one
row OR one column.
Scalars are matrices with only one row AND one column
9. Generating Matrices
A scalar can be created in MATLAB as follows:
>> x = 23;
A matrix with only one row is called a row vector. A row vector
can be created in MATLAB as follows (note the commas):
>> y = [12,10,-3]
y =
12 10 -3
A matrix with only one column is called a column vector. A
column vector can be created in MATLAB as follows:
>> z = [12;10;-3]
z =
12
10
-3
10. Generating Matrices
MATLAB treats row vector and column vector very differently
A matrix can be created in MATLAB as follows (note the
commas and semicolons)
>> X = [1,2,3;4,5,6;7,8,9]
X =
1 2 3
4 5 6
7 8 9
Matrices must be rectangular!
11. The Matrix in MATLAB
A(2,4)
A(17)
Note: Unlike C, MATLAB’s indices start from 1
12. Extracting a Sub-matrix
A portion of a matrix can be extracted and stored in a smaller
matrix by specifying the names of both matrices and the rows
and columns to extract. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and c1
and c2 specify the beginning and ending columns to be
extracted to make the new matrix.
14. Matrix Extension
>> a = [1,2i,0.56]
a =
1 0+2i 0.56
>> a(2,4) = 0.1
a =
1 0+2i 0.56 0
0 0 0 0.1
repmat – replicates and tiles a
matrix
>> b = [1,2;3,4]
b =
1 2
3 4
>> b_rep = repmat(b,1,2)
b_rep =
1 2 1 2
3 4 3 4
Concatenation
>> a = [1,2;3,4]
a =
1 2
3 4
>> a_cat =[a,2*a;3*a,2*a]
a_cat =
1 2 2 4
3 4 6 8
3 6 2 4
9 12 6 8
NOTE: The resulting matrix must
be rectangular
15. Matrix Addition
Increment all the elements of
a matrix by a single value
>> x = [1,2;3,4]
x =
1 2
3 4
>> y = x + 5
y =
6 7
8 9
Adding two matrices
>> xsy = x + y
xsy =
7 9
11 13
>> z = [1,0.3]
z =
1 0.3
>> xsz = x + z
??? Error using => plus
Matrix dimensions must
agree
16. Matrix Multiplication
Matrix multiplication
>> a = [1,2;3,4]; (2x2)
>> b = [1,1]; (1x2)
>> c = b*a
c =
4 6
>> c = a*b
??? Error using ==> mtimes
Inner matrix dimensions
must agree.
Element wise multiplication
>> a = [1,2;3,4];
>> b = [1,½;1/3,¼];
>> c = a.*b
c =
1 1
1 1
17. Matrix Element wise operations
>> a = [1,2;1,3];
>> b = [2,2;2,1];
Element wise division
>> c = a./b
c =
0.5 1
0.5 3
Element wise multiplication
>> c = a.*b
c =
2 4
2 3
Element wise power operation
>> c = a.^2
c =
1 4
1 9
>> c = a.^b
c =
1 4
1 3
18. Matrix Manipulation functions
zeros : creates an array of all zeros, Ex: x = zeros(3,2)
ones : creates an array of all ones, Ex: x = ones(2)
eye : creates an identity matrix, Ex: x = eye(3)
rand : generates uniformly distributed random numbers in [0,1]
diag : Diagonal matrices and diagonal of a matrix
size : returns array dimensions
length : returns length of a vector (row or column)
det : Matrix determinant
inv : matrix inverse
eig : evaluates eigenvalues and eigenvectors
rank : rank of a matrix
find : searches for the given values in an array/matrix.
20. Elementary Math functions
abs - finds absolute value of all elements in the matrix
sign - signum function
sin,cos,… - Trignometric functions
asin,acos… - Inverse trignometric functions
exp - Exponential
log,log10 - natural logarithm, logarithm (base 10)
ceil,floor - round towards +infinity, -infinity respectively
round - round towards nearest integer
real,imag - real and imaginary part of a complex matrix
sort - sort elements in ascending order
21. Elementary Math functions
sum,prod - summation and product of elements
max,min - maximum and minimum of arrays
mean,median – average and median of arrays
std,var - Standard deviation and variance
and many more…
23. 2D Plotting
Example 1: Plot sin(x) and cos(x) over [0,2π], on the same plot with
different colours
Method 1:
>> x = linspace(0,2*pi,1000);
>> y = sin(x);
>> z = cos(x);
>> hold on;
>> plot(x,y,‘b’);
>> plot(x,z,‘g’);
>> xlabel ‘X values’;
>> ylabel ‘Y values’;
>> title ‘Sample Plot’;
>> legend (‘Y data’,‘Z data’);
>> hold off;
29. Load and Save
Using load and save
load filename - loads all variables from the file “filename”
load filename x - loads only the variable x from the file
load filename a* - loads all variables starting with ‘a’
for more information, type help load at command prompt
save filename - saves all workspace variables to a binary
.mat file named filename.mat
save filename x,y - saves variables x and y in filename.mat
for more information, type help save at command prompt
30. Import/Export from Excel sheet
Copy data from an excel sheet
>> x = xlsread(filename);
% if the file contains numeric values, text and raw data values, then
>> [numeric,txt,raw] = xlsread(filename);
Copy data to an excel sheet
>>x = xlswrite('c:matlabworkdata.xls',A,'A2:C4')
% will write A to the workbook file, data.xls, and attempt to fit the
elements of A into the rectangular worksheet region, A2:C4. On
success, ‘x’ will contain ‘1’, while on failure, ‘x’ will contain ‘0’.
for more information, type help xlswrite at command prompt
31. Read/write from a text file
Writing onto a text file
>> fid = fopen(‘filename.txt’,‘w’);
>> count = fwrite(fid,x);
>> fclose(fid);
% creates a file named ‘filename.txt’ in your workspace and stores
the values of variable ‘x’ in the file. ‘count’ returns the number of
values successfully stored. Do not forget to close the file at the end.
Read from a text file
>> fid = fopen(‘filename.txt’,‘r’);
>> X = fscanf(fid,‘%5d’);
>> fclose(fid);
% opens the file ‘filename.txt’ which is in your workspace and loads
the values in the format ‘%5d’ into the variable x.
Other useful commands: fread, fprintf
33. Flow control
MATLAB has five flow control statements
- if statements
- switch statements
- for loops
- while loops
- break statements
34. ‘if’ statement
The general form of the ‘if’
statement is
>> if expression
>> …
>> elseif expression
>> …
>> else
>> …
>> end
Example 1:
>> if i == j
>> a(i,j) = 2;
>> elseif i >= j
>> a(i,j) = 1;
>> else
>> a(i,j) = 0;
>> end
Example 2:
>> if (attn>0.9)&(grade>60)
>> pass = 1;
>> end
35. ‘switch’ statement
switch Switch among several
cases based on expression
The general form of the switch
statement is:
>> switch switch_expr
>> case case_expr1
>> …
>> case case_expr2
>> …
>> otherwise
>> …
>> end
Example :
>> x = 2, y = 3;
>> switch x
>> case x==y
>> disp('x and y are equal');
>> case x>y
>> disp('x is greater than y');
>> otherwise
>> disp('x is less than y');
>> end
x is less than y
Note: Unlike C, MATLAB doesn’t need
BREAKs in each case
36. ‘for’ loop
for Repeat statements a
specific number of times
The general form of a for
statement is
>> for variable=expression
>> …
>> …
>> end
Example 1:
>> for x = 0:0.05:1
>> printf(‘%dn’,x);
>> end
Example 2:
>> a = zeros(n,m);
>> for i = 1:n
>> for j = 1:m
>> a(i,j) = 1/(i+j);
>> end
>> end
37. ‘while’ loop
while Repeat statements an
indefinite number of times
The general form of a while
statement is
>> while expression
>> …
>> …
>> end
Example 1:
>> n = 1;
>> y = zeros(1,10);
>> while n <= 10
>> y(n) = 2*n/(n+1);
>> n = n+1;
>> end
Example 2:
>> x = 1;
>> while x
>> %execute statements
>> end
Note: In MATLAB ‘1’ is
synonymous to TRUE and ‘0’ is
synonymous to ‘FALSE’
38. ‘break’ statement
break terminates the execution of for and while loops
In nested loops, break terminates from the innermost loop only
Example:
>> y = 3;
>> for x = 1:10
>> printf(‘%5d’,x);
>> if (x>y)
>> break;
>> end
>> end
1 2 3 4
40. Efficient Programming in MATLAB
Avoid using nested loops as far as possible
In most cases, one can replace nested loops with efficient matrix
manipulation.
Preallocate your arrays when possible
MATLAB comes with a huge library of in-built functions, use them
when necessary
Avoid using your own functions, MATLAB’s functions are more likely
to be efficient than yours.
41. Example 1
Let x[n] be the input to a non causal FIR filter, with filter
coefficients h[n]. Assume both the input values and the filter
coefficients are stored in column vectors x,h and are given to
you. Compute the output values y[n] for n = 1,2,3 where
19
y n h k x n k
[ ] [ ] [ ]
0
k
42. Solution
Method 1:
>> y = zeros(1,3);
>> for n = 1:3
>> for k = 0:19
>> y(n)= y(n)+h(k)*x(n+k);
>> end
>> end
Method 2 (avoids inner loop):
>> y = zeros(1,3);
>> for n = 1:3
>> y(n) = h’*x(n:(n+19));
>> end
Method 3 (avoids both the loops):
>> X= [x(1:20),x(2:21),x(3:22)];
>> y = h’*X;
43. Example 2
Compute the value of the following function
y(n) = 13*(13+23)*(13+23+33)*…*(13+23+ …+n3)
for n = 1 to 20
44. Solution
Method 1:
>> y = zeros(20,1);
>> y(1) = 1;
>> for n = 2:20
>> for m = 1:n
>> temp = temp + m^3;
>> end
>> y(n) = y(n-1)*temp;
>> temp = 0
>> end
Method 2 (avoids inner loop):
>> y = zeros(20,1);
>> y(1) = 1;
>> for n = 2:20
>> temp = 1:n;
>> y(n) = y(n-1)*sum(temp.^3);
>> end
Method 3 (avoids both the loops):
>> X = tril(ones(20)*diag(1:20));
>> x = sum(X.^3,2);
>> Y = tril(ones(20)*diag(x))+ …
triu(ones(20)) – eye(20);
>> y = prod(Y,2);
45. Getting more help
Where to get help?
In MATLAB’s prompt type :
help, lookfor, helpwin, helpdesk, demos
On the Web :
http://www.mathworks.com/support
http://www.mathworks.com/products/demos/#
http://www.math.siu.edu/MATLAB/tutorials.html
http://math.ucsd.edu/~driver/21d -s99/MATLAB-primer.html
http://www.mit.edu/~pwb/cssm/
http://www.eecs.umich.edu/~aey/eecs216/.html