Flumes Short Introduction to MATLAB Peter Nordin July 30, 2014 This guide is meant for mechanical-engineering students with little or no prior MATLAB experience. It introduces some useful MATLAB commands. This guide may be improved sometimes so check http://www.iei.liu.se/flumes/guides?l=en for the latest version. Contents 1 Introduction 1.1 What is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 GNU Octave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 2 Commands 2.1 Basic Commands . . . . . . . . . . . . . . 2.2 Creating Scalars, Vectors and Matrices . . 2.3 Accessing Vector and Matrix Elements . . 2.4 Accessing Struct Fields . . . . . . . . . . . 2.5 Plotting . . . . . . . . . . . . . . . . . . . 2.5.1 Line and Marker Style and Colors 2.5.2 Plot Handles and Properties . . . . 2.5.3 A Plot Example . . . . . . . . . . . . . . . . . . 1 1 2 2 2 3 3 3 3 3 Scripts and Functions 3.1 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Introduction 1.1 What is MATLAB? From the MathWorks webpage1 : R is a high-level language and interactive environment for numerical compu“MATLAB tation, visualization, and programming. Using MATLAB, you can analyze data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spreadsheets or traditional programming languages, such as C/C++ or JavaTM .” MATLAB is free to use if you are a student at Linköping University. You can find it installed on the computers in “all” of our computer labs and you can also download it and install it on your home computer using the university license (while you are a student). 1.2 GNU Octave An open-source (and free) alternative to MATLAB is GNU Octave that offers similar capabilities (at least the basic ones). Its syntax is mostly compatible to MATLAB and most examples from this guide will work in Octave too (there may be minor differences). From the webpage2 : “GNU Octave is a high-level interpreted language, primarily intended for numerical computations. It provides capabilities for the numerical solution of linear and nonlinear problems, and for performing other numerical experiments. It also provides extensive graphics capabilities for data visualization and manipulation. Octave is normally used through its interactive command line interface, but it can also be used to write non-interactive programs. The Octave language is quite similar to Matlab so that most programs are easily portable.” 2 Commands This section gives a few examples of MATLAB commands and syntax that might be useful. 2.1 Basic Commands help help command doc command format clear clear varName close all load ’data.mat’ save 1 2 List help topics Show text help for particular command Open manual page for command Change display format of values, see help for options Remove all variables Remove one (or multiple) variables Close all plot windows Load data from .mat file Save data to .mat http://www.mathworks.se/products/matlab/ (2014-01-03) http://www.gnu.org/software/octave/ (2014-01-03) 1 2.2 Creating Scalars, Vectors and Matrices a = [] a=5 a = [1 2 3 4 5 6] a = [1 2 3; 4 5 6] a = 0:0.1:1 a = linspace(start,stop,nSteps) t = linspace(Tstart,Tend,F0*Tend+1) a = sin(2*pi*f*t) a a a a = = = = 2.3 zeros(nRows, nCols) ones(nRows, nCols) eye(nRowsCols) [a, newData] Accessing Vector and Matrix Elements a = V(1) a = A(2,3) a = A(2,end) a = A(:,1) a = A(2,:) a = A(1:799) c = C1 l = length(V) s = size(M) 2.4 Create empty variable Assign/create a variable with value Create a vector (1x6 Matrix) Create a 2x3 Matrix Create a vector from zero to one with steps of 0.1 An other way to create a linear space vector Create a time vector at frequency F0 Create a data vector according to given function (t is a time vector) Create a matrix or vector of zeros Create a matrix or vector of ones Create a unit matrix Append newData (scalar or vector) to a Access element 1 in vector V Access element at row=2 column=3 Access element at row=2 last column Access elements at all rows in column 1 Access elements at row=2 all columns Extract elements 1 to 799 from A Access an element of a Cell-array Get the length of a vector Get the size of a matrix or vector (nRows,nCols) Accessing Struct Fields le.data = y le.samp le.samp.t In struct named le, add variable y as a filed named data From struct named le, access sub-struct samp and show contents From struct named le, access sub-struct samp and finally data vector t 2 2.5 Plotting plot(d) Plot vector d (element number will appear on xaxis) Plot vector t on x-axis and d on y-axis Plot t,d with red color Plot t,d with red color and marker * Plot t,d with red color, marker * and dashed lines Allows you to set additional plot properties Set the axis limits Set the x-axis label Set the y-axis label Set the plot title Set the data legend Create or open a figure, n: figure number Clear current figure Hold plots on consecutive plot commands to same figure Turns off hold Can be used to save the current figure to file (or printer) Can be used as print but with less options Print a png at 150 dpi plot(t, d) plot(t, d, ’r’) plot(t, d, ’r*’) plot(t, d, ’r*--’) plot(t, d, ’PropName’, value) axis([xmin xmax tmin ymax]) xlabel(’Text’) ylabel(’Text’) title(’Text’) legend(’Curve1’, ’Curve2’) figure(n) clf hold on hold off print saveas print(’-dpng’, ’-r150’, ’pic.png’) 2.5.1 Line and Marker Style and Colors colors bgrcmykw line types - : -. -marker types . ox+*sd See help plot for all colors lines and markers and more. 2.5.2 Plot Handles and Properties h = plot(t,d) get(h) set(h, ’PropName’, value) gca, gco, gcf Get a handle (h) to the plot object List all properties of a plot object, or get a particular one Lets you change a property after the plot has been drawn Returns a handle to the current Axis, GraphicsObject or Figure. Works with get() and set() commands. Use gca properties if you want to change axis appearance such as label font size. 2.5.3 A Plot Example figure (1) clf h o l d on p l o t ( t , y0 , ’ b ’ ) p l o t ( t , y1 , ’ k−− ’ ) hold o f f % % % % % % Open f i g u r e 1 Clear the f i g u r e Begin h o l d i n g p l o t data P l o t t , y with b l u e c o l o r p l o t t , y1 , with a dashed b l a c k l i n e Stop h o l d i n g p l o t data 3 % Now s e t t h e s i z e o f c u r r e n t f i g u r e and e x p o r t f i g u r e a t 150 d p i % g c f means c u r r e n t f i g u r e s e t ( g c f , ’ PaperUnits ’ , ’ c e n t i m e t e r s ’ ) s e t ( g c f , ’ P a p e r S i z e ’ , [ 1 2 , 1 0 ] , ’ P a p e r P o s i t i o n ’ , [ 0 0 12 1 0 ] ) p r i n t ( ’−dpng ’ , ’−r 1 5 0 ’ , ’ p i c t u r e . png ’ ) 3 Scripts and Functions 3.1 Scripts You can write programs or scripts in .m files. A script is a file with multiple consecutive commands. An example is the plot example in section 2.5.3. The following characters have special meaning in scripts: % Write a comment after the % sign %% Start a New Matlab section (can be executed with ctrl+enter) 3.2 Functions A function is a self contained group of commands that can be called multiple times. You can reuse the code that is written in one place only. Functions usually take arguments and return results. In MATLAB you can hover a function with your mouse and press F1, to see its help. You can also write you own functions. This is an example of a reusable MATLAB function f u n c t i o n [ r e t 1 , r e t 2 ] = doSomethingCool ( arg1 , arg2 , a r g 3 ) % This i s t h e h e l p t e x t % doSomthingCool d o e s something c o o l and h e r e we d e s c r i b e what % Syntax : [ r e t 1 , r e t 2 ] = doSomethingCool ( arg1 , arg2 , a r g 3 ) % Arguments : % a r g 1 = D e s c r i p t i o n o f argument 1 % a r g 2 = D e s c r i p t i o n o f argument 2 % a r g 3 = D e s c r i p t i o n o f argument 3 % Returns : % ret1 = Description of return value 1 % ret2 = Description of return value 2 >> Your code g o e s h e r e << % I t s h o u l d do something c o o l and c r e a t e t h e r e t 1 and r e t 2 % based on i n p u t t h e i n p u t arguments You can call the function like this: [ x y ] = doSomethingCool ( 1 , 2 , ’ monkey ’ ) ; The x and y variables will get the ret1 and ret2 values. Inside the function arg1 will be 1, arg2 will be 2 and arg3 will be the text string monkey 4
© Copyright 2026 Paperzz