Matlabtalk2
-
Upload
anand-balaji -
Category
Documents
-
view
219 -
download
0
Transcript of Matlabtalk2
-
7/28/2019 Matlabtalk2
1/43
MATLAB
Programming I
Joy
-
7/28/2019 Matlabtalk2
2/43
Outline
Examples What is Matlab?
History
Characteristics
Organization of Matlab Toolboxes
Basic Applications Programming
-
7/28/2019 Matlabtalk2
3/43
Example I
Obtain the result of matrix multiply
Matlab Code
>>A=[4,6; 9,15; 8,7];
>>B=[3,24,5; 7,19,2];
>>C=A*BC =
54 210 32
132 501 75
73 325 54
4 63 24 5
9 157 19 2
8 7
-
7/28/2019 Matlabtalk2
4/43
C Code
#include #include #include #include
#include #include
using namespace std;typedef vector Mat;void input(istream& in, Mat& a);Mat matrix_product(const Mat& a, const Mat& b);
void print(const Mat& a);
-
7/28/2019 Matlabtalk2
5/43
C Codes
int main(int argc, char *argv[]){ifstream in1 ( "Matrix A.txt" );ifstream in2 ( "Matrix B.txt" );int row, row1, col, col1;in1>>row>>col;in2>>row1>>col1;
Mat a(row, vector(col));input(in1, a);Mat b(row1, vector(col1));
input(in2, b);
print(matrix_product(a,b));system("PAUSE");return EXIT_SUCCESS;
}
-
7/28/2019 Matlabtalk2
6/43
C Code Cond.void input(istream& in, Mat& a)
{for(int i = 0; i < a.size(); ++i)
for(int j = 0; j < a[0].size(); ++j)in>>a[i][j];
}
void print(const Mat& a){
for(int i = 0; i < a.size(); ++i){ cout
-
7/28/2019 Matlabtalk2
7/43
C Code Cond.
Mat matrix_product(const Mat& a, const Mat& b){
Mat c(a.size(), vector(b[0].size()));for(int i = 0; i < c.size(); ++i)for(int j = 0; j < c[0].size(); ++j){c[i][j] = 0;for(int k = 0; k < b.size() ; ++k)
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}return c;
}
-
7/28/2019 Matlabtalk2
8/43
Example II
Calculate the transpose of the matrix:
Matlab Code
>>A=[3,17,2;5,19,7;6,4,54]
>>A^(-1)
ans =-0.9327 0.8505 -0.0757
0.2131 -0.1402 0.0103
0.0879 -0.0841 0.0262
3 17 2
5 19 7
6 4 54
-
7/28/2019 Matlabtalk2
9/43
What is MATLAB?
Abbreviation of MATrix LABoratory
Is a high-performance language for
technical computing
It integrates computation, visualization,
and programming in an easy-to-useenvironment where problems andsolutions are expressed in familiarmathematical notation.
-
7/28/2019 Matlabtalk2
10/43
Usage of MATLAB
Math and computation Algorithm development
Data acquisition
Modeling, simulation, and prototyping Data analysis, exploration, and visualization
Scientific and engineering graphics
Application developmentincluding graphical user interface building
-
7/28/2019 Matlabtalk2
11/43
History
In 1970s Dr.Cleve MolerBased on Fortran on EISPACK and LINPACKOnly solve basic matrix calculation and graphic
1984 MathWorks Company by Cleve Moler and
Jack LittleMatlab 1.0 based on CIncluded image manipulations, multimedia etc.toolboxes
In 1990 run on WindowsSimulink, Notebook, Symbol Operation, etc.
21 Century
-
7/28/2019 Matlabtalk2
12/43
Main Features
Powerful tool for matrix calculationsBasic data type is double complex matrix with subscript is 1
High efficient/reliable algorithms
Multi-paradigm
- interactive environment (no compiler)
- programming
Most input/output parameters in Matlab
functions are variable User friendly with extensively help system
-
7/28/2019 Matlabtalk2
13/43
MATLAB SYSTEM
Develop Tools
Toolboxes
Data-Accessing Tools
Stateflow
Generating-Codes Tools
Module Libraries
Third parties modules
Applications
DATA
C
Simulink
MATLAB
-
7/28/2019 Matlabtalk2
14/43
Buildup of MATLAB
Development EnvironmentMATLAB desktop and Command Window, a command history, an editorand debugger, and browsers for viewing help, the workspace, files, and thesearch path.
The MATLAB Mathematical Function LibraryA vast collection of computational algorithms ranging from elementary
functions to more sophisticated functions The MATLAB Language
A high-level matrix/array language with control flow statements,functions, data structures, input/output, and object-orientedprogramming features
GraphicsDisplay vectors and matrices as graphstwo-dimensional and three-dimensional data visualizationimage processinganimation and presentation graphics
The MATLAB Application Program Interface (API)Interchange the C/Fortran codes with Matlab codes
-
7/28/2019 Matlabtalk2
15/43
Basic Applications I
Matrices and ArraysGenerating Arrays/Matrices
Elementary Matrices:
sum, transpose, diagonal, subscriptsVariables: does not require any typedeclarations or dimension statements
Operators: +,-,*,/, ^, etc.Examples of Expressions
-
7/28/2019 Matlabtalk2
16/43
Generating Matrices
Directly enterA = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
Use Functions
Example: B = zeros(1,5) row vector/arrayC = ones(7,1)column vector/array
D = rand(5,8,3) multiple dimension matrix
Load/Import from files
zeros All 0sones All 1s
rand Uniformly distributed random elements
randn Normally distributed random elements
-
7/28/2019 Matlabtalk2
17/43
Elementary Matrices
>>D=rand(3,2,3)D(:,:,1) = D(:,:,2) = D(:,:,3) =
0.9501 0.4860 0.4565 0.4447 0.9218 0.40570.2311 0.8913 0.0185 0.6154 0.7382 0.93550.6068 0.7621 0.8214 0.7919 0.1763 0.9169
>> sum(D(:,1,1))ans =
1.7881>> E=D(:,:,2)'E =
0.4565 0.0185 0.82140.4447 0.6154 0.7919
>> a=diag(D(:,:,3))a =
0.92180.9355
>> F=[D(1,:,1),D(2,:,3); D(1,:,1)+1, D(2,:,3)-1]F =
0.9501 0.4860 0.7382 0.93551.9501 1.4860 -0.2618 -0.0645
>>F(:,2)=[]F =
0.9501 0.7382 0.93551.9501 -0.2618 -0.0645
>> F(2:1:4)=[]F =
0.9501 0.9355 -0.0645
-
7/28/2019 Matlabtalk2
18/43
Examples of Expression
>>rho = (1+sqrt(5))/2rho =
1.6180
>>a = abs(3+4i)
a =
5
>>huge = exp(log(realmax))
huge =
1.7977e+308 =1.8X10308
-
7/28/2019 Matlabtalk2
19/43
Basic Application II
Graphic
-
7/28/2019 Matlabtalk2
20/43
Programming
Flow ControlSelector: if, switch & case
Loop: for, while, continue, break, try & catch
Other: return Other Data Structures
Multidimensional arrays, Cell arrays, Structures,etc.
Scripts and Functions
-
7/28/2019 Matlabtalk2
21/43
Flow Control Examples I
Selector:2-way:ifrand < 0.3 %Condition
flag = 0; %then_expression_1else
flag = 1; %then_expression_2end %endifMultiple-ways:
ifA > B | switch (grade)'greater | case 0
elseifA < B | Excellent
'less | case 1elseifA == B | Good
'equal | case 2else | Average
error('Unexpected situation') | otherwiseend | Failed
| end
-
7/28/2019 Matlabtalk2
22/43
Flow Control Examples II
Loop>>Generate a matrix
fori = 1:2
forj = 1:6
H(i,j) = 1/(i+j);end
end
>>H
H =
0.5000 0.3333 0.2500 0.2000 0.1667 0.1429
0.3333 0.2500 0.2000 0.1667 0.1429 0.1250
-
7/28/2019 Matlabtalk2
23/43
Loop Cond.>>%Obtain the result is a root of the polynomial x3 - 2x 5a = 0; fa = -Inf;b = 3; fb = Inf;while b-a > eps*b
x = (a+b)/2;fx = x^3-2*x-5;ifsign(fx) == sign(fa)
a = x; fa = fx;else
b = x; fb = fx;end
end>>x
x =2.09455148154233
-
7/28/2019 Matlabtalk2
24/43
Scripts
MATLAB simply executes the commands foundin the file
Example
% Investigate the rank of magic squares
r = zeros(1,32); %generation a row array 1X 32% ; tell the system does not display
% the result on the screen
forn = 3:32
r(n) = rank(magic(n));end
r
bar(r) %display r in bar figure
-
7/28/2019 Matlabtalk2
25/43
Scripts Cond.
Note:No input/output parameters
(Different from functions! )
Write the script in editor, which can beactivated by command edit in command
window, save it with its specific name
Next time you want to execute the script justcall the name in the command window
-
7/28/2019 Matlabtalk2
26/43
Functions
Functions are M-files that can accept inputarguments and return output arguments.The names of the M-file and of the
function should be the same.
-
7/28/2019 Matlabtalk2
27/43
Function Example I
Background of AICAIC is used to compare the quality of nestedmodels
AIC requires a bias-adjustment in small samplesizes
1
2 ln( ) 2
2 ( 1)
2 ln( ) 2 1
min( )
exp( 0.5 )
exp( 0.5 )
i i
i
i R
r
r
AIC likelihood K
K K
AICad likelihood K n K
delta AIC AIC
deltaw
delta
-
7/28/2019 Matlabtalk2
28/43
Function Head (Comments)
%AICad Function%Date:Dec.29th, 2008%Purpose: Calculate the adjusted% Akaikes Information Criteria (AIC)
%InPut: AIC% n (the sample size)% K (the number of parameters in the model)%OutPut: AICad
% delta% weight%Functions Called: None%Called by: None
-
7/28/2019 Matlabtalk2
29/43
IN Command Window
>>AIC=[-123; -241.7; -92.4; -256.9];>>n=12;>>K=[4;8;2;6];>>[AICad, delta, w] = CalAIC(AIC, n, K)
AICad = delta = w =
-83.0000 89.9000 0.0000-97.7000 75.2000 0.0000
-80.4000 92.5000 0.0000-172.9000 0 1.0000
-
7/28/2019 Matlabtalk2
30/43
M file
function[AICad,delta,w]=CalAIC(AIC,n,K)AICad = AIC+2.*K.*(K+1);
a = min(AICad);
delta = AICad - a;
b = exp(-0.5.*delta);
c = sum(b);
w = b./c;
-
7/28/2019 Matlabtalk2
31/43
Function Example II
Background of PCAComparing more than two communities or samples
Sample Post Oak Red Oak Water Oak
1 66 25 24
2 48 30 31
3 26 55 42
4 15 20 495 11 50 58
combine post post red red water water Y w x w x w x
-
7/28/2019 Matlabtalk2
32/43
Background of PCA
Cond.
Principal Components Analysis (PCA) It finds weighted sums of samples or
observations (linear combinations) that arehighly correlated with the values of the responsevariables (e.g., species abundances)
PCA objectively chooses these weights in such a way
as to maximize the variance in the weighted sums
Based on correlations between response variables
.
-
7/28/2019 Matlabtalk2
33/43
Function Head
%Principle Component Analysis Function%Date:Dec.29th, 2008
%Purpose: Obtain the axis scores of PCA
%InPut: the abundance of 3 species
% in 5 different samples
%OutPut: sample scores of PCA axis%Functions Called: None
%Called by: None
-
7/28/2019 Matlabtalk2
34/43
IN Command Window
>>a=[66;48;26;15;11];>>b=[25;30;55;20;50];>>c=[24;31;42;49;58];>>[score1, score2]=PCA(a,b,c)
score1 = score2 =-2.2233 -0.1963-1.1519 -0.07430.8734 -1.0888
0.4871 1.51202.0147 -0.1526
-
7/28/2019 Matlabtalk2
35/43
M file
function[x11,x12,x13,x21,x22,x23]=PCA(a,b,c)
%Calculate the mean and population standard deviation of 3 speciesfor i=1:5
d(i)=(a(i)-mean(a))^2;stda=sqrt(sum(d)/5);e(i)=(b(i)-mean(b))^2;
stdb=sqrt(sum(e)/5);f(i)=(c(i)-mean(c))^2;stdc=sqrt(sum(f)/5);
end%Obtain the z-scores of 3 species
for i=1:5za(i)=(a(i)-mean(a))/stda;zb(i)=(b(i)-mean(b))/stdb;zc(i)=(c(i)-mean(c))/stdc;
endN=[za',zb',zc'];
-
7/28/2019 Matlabtalk2
36/43
M file Cond.
%Obtain the original correlation matrixM=[1,corr(a,b),corr(a,c);corr(a,b),1,corr(b,c);corr(a,c),corr(b,c),1];[V1,D1]= eig(M); %Calculate the eigenvector and eigenvaluesweight1=V1(:,3); %Get the maximum eigenvectorscore1=N*weight1;
%We use the exact same procedure that we used for axis 1,%except that we use a partial correlation matrix%The partial correlation matrix is made up of all pairwise correlations%among the 3 species, independent of their correlation with the axis 1
%sample scores. Hence, axis 2 sample scores will be uncorrelated%with (or orthogonal to) axis 1 scores.
-
7/28/2019 Matlabtalk2
37/43
M file Cond.
new=[a,b,c,score1];M2=[1,corr(a,b),corr(a,c),corr(a,score1);
corr(a,b),1,corr(b,c),corr(b,score1);corr(a,c), corr(b, c), 1, corr(c,score1);corr(a,score1),corr(b,score1),corr(c,score1),1];
for i=1:3
for j=1:3corrnew(i,j)=M2(i,j);
endendg=[M2(4,1)*M2(4,1),M2(4,1)*M2(4,2),M2(4,1)*M2(4,3);
M2(4,2)*M2(4,1),M2(4,2)*M2(4,2),M2(4,2)*M2(4,3);M2(4,3)*M2(4,1),M2(4,3)*M2(4,2),M2(4,3)*M2(4,3)];
corrmatrix=corrnew-g;[V2,D2]=eig(corrmatrix);weight2=V2(:,3); %signs needs to be checked with JMP
score2=N*weight2;
-
7/28/2019 Matlabtalk2
38/43
MATLAB in MCSR
Matlab is available on willow and sweetgum www.mcsr.olemiss.edu
http://www.mcsr.olemiss.edu/mailto:[email protected]:[email protected]://www.mcsr.olemiss.edu/ -
7/28/2019 Matlabtalk2
39/43
-
7/28/2019 Matlabtalk2
40/43
-
7/28/2019 Matlabtalk2
41/43
Enter matlab can activate Matlab in willowor sweetgum
Use ver to obtain the version of Matlab,
which can tell you which toolboxes ofMatlab in that machine
Price of personal purchase is 500$ include updatereleases (only include MATLAB & Simulink)
You need pay separate fee for each toolbox such asstatistical, bioinformatics, etc
-
7/28/2019 Matlabtalk2
42/43
Take Home Message
-
7/28/2019 Matlabtalk2
43/43