Matlab®: Academic Resource Center
Matlab®: Academic Resource Center
Matlab®: Academic Resource Center
Workshop goals
We will be discussing: Elementary Operations The command window Vector and Matrices Element by Element Operations Graphics Scripts Functions Flow Control Symbolic Computation
We will NOT be discussing: MATLAB Environment Specific Toolboxes Import, Export data Graphic User Interfaces
Elementary Operations
The four elementary arithmetic operations in MATLAB addition, subtraction, multiplication, and division are represented by the operators +, -, *, and /, respectively: >> (20+10-4*5)/2 ans = 5 The operator \ is for left division, where the denominator is at the left, rather than the right. Compare / and \: >> 2/4 ans = 0.5000 >> 2\4 ans = 2 The symbol ^ stands for the power operator: >> 5^2 ans = 25
MATLAB can handle complex numbers and infinite numbers: >> sqrt(-1) ans = 0 + 1.0000i >> 1/0 ans = Inf
To suppress the display in the Command Window of the result of the assignment, put a semicolon at the end of the statement: >>c=a+b;
You can see the value of the variable by simply typing the variable: >> c c= 8 *note MATLAB is case sensitive
>> M= [1, 2, 3; 4, 5, 6]
M= 1 2 3 4 5 6
OR
>> M= [1, 2, 3 4 5 6]
M= 1 2 4 5
The elements of a row: separated by comma or space Rows: separated by semicolon or carriage return Elements of a matrix can be accessed or replaced individually: M(row, column):
3 6
Shorthand notation for a sequence: the colon (:) operator. A colon placed between two numbers generates the vector of numbers from left limit to right limit: >> v=[-1:4] v= -1 0 1 2 3 4 Default increment is 1, but can be changed: >> W=[-1:0.5:2; 6:-1:0; 1:7] W= -1.0000 -0.5000 0 0.5000 1.0000 1.5000 2.0000 6.0000 5.0000 4.0000 3.0000 2.0000 1.0000 0 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000
Matrix arithmetic
The rules that govern matrix arithmetic in linear algebra apply in MATLAB. A detailed overview of these rules is beyond the scope of this workshop.
Multiplying and adding a matrix by scalar >> 2*W ans = -2 -1 0 1 2 3 4 12 10 8 6 4 2 0 2 4 6 8 10 12 14 Vector and matrix multiplication requires that They are conformable. >> A*C ans = 33 32 115 >> C*A % conformable because C is (3 x 1) and % A is (3 x 3) Only arrays of the same size may be added or subtracted. >> A= [1, 2, 6; 2:4; 10:0.5:11]; >> B= [4, 7, 14; 1, 5, 7; 7, 7, 5]; >> A-B ans = -3.0000 -5.0000 -8.0000 1.0000 -2.0000 -3.0000 3.0000 3.5000 6.0000 >> C=[5;2;4] C= 5 2 4 >> A-C ??? Error using ==> minus Matrix dimensions must agree.
% nonconformable because C is (3 x 1) % and A is (3 x 3) ??? Error using ==> mtimes Inner matrix dimensions must agree.
Element by Element
(What makes MATLAB so unique and powerful)
To perform element-by-element operations on matrices and vectors use a period ( . ) before the operator symbol: Basically same as: For n=1:length(A) For k=1:length(B) A(n, k)*B(n, k)=ans(n, k) end
>> A=rand(4,4); >> B=sin(rand(4,4)); >> A.*B ans = 0.2518 0.1064 0.1509 0.2639 0.3143 0.1148 0.0159 0.1459 >> A.^2 ans = 0.4671 0.1095 0.4957 0.1800 0.1956 0.0730 0.0004 0.0388
Graphics
2D Plots
x=linspace(0,2,30); %create a vector of 30 values %equally spaced between 0 and 2 y = x.*exp(-x); %calculate the y vales plot(x, y) %plot y versus x grid %add grid lines to the current axes xlabel('Distance') %label x axes ylabel('Concentration') %label y axes title('Figure 1: y = xe^-x') %add title of the graph title('Figure 1: y = xe^-^x') %add title of the graph gtext('anywhere') %place text with mouse text(1, 0.2, '(1,0.2)') %place text with specific point
2D Plots
plot(x,y, '+', x, x.*sin(x)) subplot(2,1,2), plot(x,x.*sin(x)) subplot(2,1,1), plot(x,x.*cos(x)) subplot(2,1,2), plot(x,x.*sin(x))
2D Plots control
Axis limits can be modified using the axis command. >> axis ans = 0 2 0 2 Try the following and observe what happens. >> axis([0, 1.5, 0, 1.5]) shg command shows the current graphics window. It is possible to use more than one graphics window by using the figure(n). Also an easy way to plot a function is to use fplot(FUN, LIMS) that plots FUN between the xaxis limits LIMS = [XMIN XMAX]. >> figure(2) %creates a second figure window >> fplot('x*exp(-x)', [0, 2])
3D plots
A 3-D curve can be shown by the plot3 command:
3D plots
Surfaces can be shown in many ways: >> [x, y] =meshgrid(-pi:pi/10:pi, -pi:pi/10:pi); >> z=cos(x).*cos(y); >> surf(x,y,z)
3d plots
Also try the following commands: >> mesh(x, y, z) >> view(30, 60) You may make the graph look better by using the shading command >> shading interp %controls the color shading of surface To see the color scale use colorbar >> colorbar
2D plots
We can show different z-levels on a system of coordinates by its contour lines. >> contour(x,y,z) Another method is the pseudocolor plot that assigns different colors to different z-values. >> pcolor(x,y,z) >> colorbar >> shading interp
Scripts
Lets calculate the volume of an ideal gas as a function of pressure and temperature. Type the following command into the editor: Save the file as ideal_gas.m and type ideal_gas in the command window % idea_gas.m - A simple script file % Calculates the volume of an ideal gas % clear all; clc; %clear all previous variables and command window disp(' Calculating the volue of an ideal gas.') R=8314; %gas constant T=input(' Vector of temperatures (K) = '); %input function call for user input P=input(' Pressure (bar) = ')*1e5; V=R*T/P; %Ideal gas law %plotting the result plot(T,V) xlabel('T (K)') ylabel('V (m^3/kmol)') title('Ideal Gas Volume vs Temperature')
Scripts: Diary
A practical method for beginers to create a script is using diary. You can start creating a diary by typing: >> diary mydiary Then start your statements one by one in the command window one by one, see the results at each step, and make corrections if necessary. When you get your desired results, close the diary: >> diary off Now you can develop a script by editing the file mydiary, delete the unnecessary commands and output, and save it as an M-file.
Functions
The first line of the function always begins with the word function. This is followed by The output argument(s) Equality sign Name of the function And input arguments
function V = ideal_gas_func(T, P) R=8314; %gas constant for k = 1:length(P) V(k,:)= R*T/P(k); % ideal gas law end
or
V=R*T./P % ideal gas law
Symbolic Computation
The Symbolic Math Toolbox enables one to perform computations using symbolic mathematics. Students are strongly encouragaed to qalk through the Symbolic Math demos that are provided ( see Help?demos/Toolboxes/Symbolic Math) To create a symbolic variable use the command sym( ) : >> y= sym(y) y= y >> om=sym(omega) om = omega
(d) The function is solved for a instead of x. >> x= solve('a*x^2+b*x+c=5', 'a') x= -(c + b*x - 5)/x^2 (e) Solution of two simultaneous algebraic equations. >> [X1, X2]= solve('aX1-bX1*X2=0',... '-g*X2+f+X1*X2=0', 'X1, X2') X1 = (aX1*g - bX1*f)/aX1 X2 = aX1/bX1
>> y = dsolve('Dy+ 4*y = exp(-t)') y= 1/(3*exp(t)) + C2/exp(4*t) Solve the same differential equation with the initial condition y(0)=2: >> y = dsolve('Dy+ 4*y = exp(-t)', 'y(0)=2') y= 1/(3*exp(t)) + 5/(3*exp(4*t)) Set the range of the independent variable tt, evaluate the dependent variable y. >> tt=[0:.1:5]; >> for i=1:length(tt) t=tt(i); yy(i)=eval(y); end >> plot(tt, yy)
>> [y1, y2]=dsolve('Dy1 + 4*y2= exp(-t)', 'Dy2=-y1', 'y1(0)=1, y2(0)=2') y1 = 1/(3*exp(t)) + 2/exp(2*t) - (4*exp(2*t))/3 y2 = 1/(3*exp(t)) + 1/exp(2*t) + (2*exp(2*t))/3 Set the range of the independent variable, evaluate the dependent variable for this range, and plot the profile: >> t=[0:.01:1]; yy1=eval(y1); yy2=eval(y2); >> plot(t,yy1,':', t,yy2)
Symbolic Integration
Another example of integration: >> syms x a f Re e T >> int('a*T+b*T^2+c*T^4', T) ans = (T^2*(6*c*T^3 + 10*b*T + 15*a))/30
Limits of integration may be used: >> int('a*T+b*T^2+c*T^4', 'T', 298, 500) ans = 80598*a + (98536408*b)/3 + (28899927176032*c)/5
Workshop goals
MATLAB is a huge program, therefore it is impossible to cover all of it in one workshop. We will not be discussing the MATLAB Environment in specifics which includes customizing the environment, and setting paths to certain directories. Also we will not be going into the specifics of programming flow control since MATLAB follows C type programming instructions. Also we will not be detailing any specific toolboxes or many built in functions which are beyond the scope of an introductory workshop. Furthermore, with the help function detailed in the end of this workshop, students will be able to use MATLABs more advanced tools.
Variable Formats
All computations in MATLAB are done in double precision. The precision of the calculation is independent of the formatted display. The results of calculation are normally displayed, or printed, with only five significant digits. The format command may be used to switch between different display formats. >> d =exp(pi) All of the different variations of t he format d= 23.1407 command may be viewed by getting the help >> format long, d for format (type help format).
d= 23.140692632779267 >> format short e, d d= 2.3141e+001 >> format long e, d d= 2.314069263277927e+001 >> format short, d d= 23.1407