Getting Started With Matlab: CDR Sunil Tyagi Naval Wing MILIT, Girinagar
Getting Started With Matlab: CDR Sunil Tyagi Naval Wing MILIT, Girinagar
Getting Started With Matlab: CDR Sunil Tyagi Naval Wing MILIT, Girinagar
MATLAB Desktop
When you start MATLAB, the desktop appears in its default layout
MATLAB Desktop
The desktop includes these panels: Current Folder Access your files. Command Window Enter commands at the command line, indicated by the prompt (>>). Workspace Explore data that you create or import from files. Command History View or rerun commands that you entered at the command line.
Working in MATLAB
As you work in MATLAB, you : Issue commands that create variables Call functions. For example: create a variable named a by typing this statement at the command line: a=1 or b=18 MATLAB adds variable a and b to the workspace and displays the result in the Command Window. When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of your calculation. For example: sin(a)
Working in MATLAB
If you end a statement with a semicolon, MATLAB performs the computation, but suppresses the display of output in the Command Window. e = a*b; You can recall previous commands by pressing the upand down-arrow keys, and . Press the arrow keys either at an empty command line or after you type the first few characters of a command. For example, to recall the command b = 2, type b, and then press the up-arrow key.
Array Indexing
Array Indexing Every variable in MATLAB is an array that can hold many numbers. When you want to access selected elements of an array, use. For example: indexing Consider the 4-by-4 magic square A: A = magic(4) There are two ways to refer to a particular element in an array. The most common way is to specify row and column subscripts, such as: A(4,2)
Array Indexing
Less common, but sometimes useful, is to use a single subscript that traverses down each column in order: A(8) Using a single subscript to refer to a particular element in an array is called linear indexing. If you try to refer to elements outside an array, MATLAB throws an error. test = A(4,5) However, you can specify elements outside the current dimensions. The size of the array increases to accommodate the newcomers. A(4,5) = 17
Array Indexing
To refer to multiple elements of an array, use the colon operator, which allows you to specify a range of the form start:end. For example: list the elements in the first three rows and the second column of A: A(1:3,2) The colon alone, without start or end values, specifies all of the elements in that dimension. For example, select all the columns in the third row of A: A(3,:) The colon operator also allows you to create an equally spaced vector of values using the more general form start:step:end. For example: B = 0:10:100
Array Indexing
A= 16 2 5 11 9 7 4 14 3 13 10 8 6 12 15 1 0 0 0 17
Index submatrices using vectors of row and column indices >> A([2 3],[1 2]) Ordering of indices is important! >> B=A([3 2],[2 1]) >> B=[A(3,2),A(3,1);A(2,2),A(2,1)] Both gives
ans = 5 9 11 7
B= 7 11 9 5
Workspace
The workspace contains variables that you create within or import into MATLAB from data files or other programs. For example, these statements A = magic(4); B = rand(3,5,2); creates variables A and B in the workspace The variables appear in the Workspace pane on the desktop.
Workspace
You can view the contents of the workspace using whos. >> whos Name A B Size 4x4 3x5x2 Bytes Class 128 double 240 double Attributes
Variables with class are high precision variable each will have 8 Bytes Workspace variables do not persist after you exit MATLAB. To save your data for later use with the save command, save myfile.mat
Workspace
Saving preserves the workspace in your current working folder in a compressed file with a .mat extension, called a MAT-file. To clear all the variables from the workspace, use the clear command. Restore data from a MAT-file into the workspace using load. load myfile.mat Character Strings A character string is a sequence of any number of characters enclosed in single quotes. You can assign a string to a variable. myText = 'Hello, world';
Character Strings
myText is an array, like all MATLAB variables. The class or data type of a Character String is char, which is short for character. Each character of character string will have 2 bytes. >> whos myText Name Size Bytes Class Attributes myText 1x12 24 char
To convert numeric values to strings, use functions, such as num2str f = 71; c = (f-32)/1.8; tempText = ['Temperature is ',num2str(c),'C'] tempText = Temperature is 21.6667C
Workspace
The workspace contains variables that you create within or import into MATLAB from data files or other programs. For example, these statements create variables A and B in the workspace. A = magic(4); B = rand(3,5,2); You can view the contents of the workspace using whos. The variables also appear in the Workspace pane on the desktop.
Workspace
Workspace variables do not persist after you exit MATLAB. Save your data for later use with the save command save myfile.mat Saving preserves the workspace in your current working folder in a compressed file with a .mat extension, called a MAT-file. To clear all the variables from the workspace, use the clear command. Restore data from a MAT-file into the workspace using load. load myfile.mat
Workspace
diary command Save text of MATLAB session. diary SUNIL (file name)
causes a copy of all subsequent command window input and resulting command window output to be stored into the named file SUNIL. If no file is specified, the file 'diary' is used. diary OFF suspends it. diary ON turns it back on
Functions
MATLAB provides a large number of functions that perform computational tasks. Functions are equivalent to subroutines in other programming languages. Suppose that your workspace includes variables A and B, such as a = [1 3 5]; b = magic(6); To call a function, enclose its input arguments in parentheses: For example max function: max(a); Output from a function by assigning it to a variable: Max_a = max(a);
Functions
When there are multiple output arguments, enclose them in square brackets: [max_a,location] = max(a); b(:) would arrange all element of matrix B in a single column what do you expect from following: [maxb,location] = max(b) and [maxb,location] = max(b(:))
Plots
Line Plots To create two-dimensional line plots, use the plot function. For example, plot the value of the sine function from 0 to 2: x = 0:pi/100:2*pi; y = sin(x); plot(x,y)
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1
Line Plots
You can label the axes and add a title. xlabel('x') ylabel('sin(x)') title('Plot of the Sine Function')
Plot of the Sine Function 1 0.8 0.6 0.4 0.2 sin(x) 0 -0.2 -0.4 -0.6 -0.8 -1
3 x
Line Plots
By adding a third input argument to the plot function, you can plot the same variables using a red dashed line. plot(x,y,'r--')
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1
Line Plots
To add plots to an existing figure, use hold. x = 0:pi/100:2*pi; 1 y = sin(x); 0.8 plot(x,y) 0.6 hold on 0.4 y2 = cos(x); 0.2 plot(x,y2,'r:') 0 legend('sin','cos') -0.2
-0.4 -0.6 -0.8 -1
sin cos
Alternatively you can give multiple argument to the plot function. Like: plot(x,y, x,y2,'r:')
Subplots
You can display multiple plots in different subregions of the same window using the subplot function. For example, create four plots in a 2-by-2 grid x = 0:pi/100:2*pi; y = sin(x); y2 = cos(x); y3=2*sin(2*x); subplot(2,2,1); plot (x,y); title('Sin (X)'); subplot(2,2,2); plot (x,y,'r--'); title('Sin (X) plotted in red dashes'); subplot(2,2,3); plot (x,y2); title('Cos (X)'); subplot(2,2,4); plot (x,y3); title('2*sin(2*x)');
Subplots
You get a plot like this:
Sin (X) 1 0.5 0 -0.5 -1 1 0.5 0 -0.5 -1 Sin (X) plotted in red dashes
4 Cos (X)
4 2*sin(2*x)
1 0.5 0 -0.5 -1
2 1 0 -1 -2
Scripts
The simplest type of MATLAB program is called a script. A script is a file with a .m extension that contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line. To create a script, use the edit command, edit plotrand This opens a blank file named plotrand.m. Enter some code that plots a vector of random data: n = 50; r = rand(n,1); plot(r)
Scripts
For example, let us save the commands used to demonstrate working of subplot into a script file named subplot_example.m