Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
كارگاه آشنايي با نرم افزار متلب
در متلببرنامه نويسي
دكتر ايوب جعفري
What is MATLAB?
• Data processing and visualization tools– Easy, fast manipulation and processing of complex data
– Visualization to aid data interpretation
– Production of publication quality figures
• High-level programming languages– Can write extensive programs, applications,…
– Faster code development than with C, Fortran, etc.
– Possible to “play” with or “explore” data – don’t have to write a standalone program to do a predetermined job
Getting Started: Windows
Just enter ‘matlab’ or ‘matlab &’ on the command line
Might need to run ‘app setup matlab’ or add this to your .cshrc file
Getting started – linux (SEE)
MATLAB User Environment
Workspace/VariableInspector
Command History
Command Window
Getting help
There are several ways of getting help:
Basic help on named commands/functions is echoed to the command window by:
>> help command-name
A complete help system containing full text of manuals is started by:
>> helpdesk
Accessing the Help Browser via the Start Menu
Help Browser
• Contents - browse through topics in an expandable "tree view"• Index - find topics using keywords• Search - search the documentation. There are four search types available:
• Full Text - perform a full-text search of the documentation• Document Titles - search for word(s) in documentation section titles• Function Name - see reference descriptions of functions• Online Knowledge Base - search the Technical Support Knowledge
Base• Demos – view and run product demos
Contents
Index
Search
Demos
Other sources of help
• www.mathworks.com– Help forums, archived questions & answers, archive
of user-submitted code
• http://lists.leeds.ac.uk/mailman/listinfo/see-matlab– Mailing list for School of Earth & Environment
self-help from other users within the school (31 at last count)
Modifying the MATLAB Desktop Appearance
Returning to the Default MATLAB Desktop
The Contents of the MATLAB Desktop
Workspace Browser
Array EditorFor editing 2-D numeric arrays
double-click
Command History Window
Current Directory Window
Calculations on the command Line
>> -5/(4.8+5.32)^2ans =
-0.048821
>> (3+4i)*(3-4i)ans =
25
>> cos(pi/2)ans =6.1232e-017
>> exp(acos(0.3))ans =
3.547
>> a = 2;
>> A = 5;
>> a^A
ans =
32
>> x = 5/2*pi;
>> y = sin(x)
y =
1
>> z = asin(y)
z =
1.5708
Variables are case sensitive
Use parentheses ( ) for function inputs
Semicolon suppresses screen output
MATLAB as a calculator Assigning Variables
Numbers stored in double-precision floating point format
Results assigned to “ans” if name not given
The WORKSPACE
• MATLAB maintains an active workspace, any variables (data) loaded or defined here are always available.
• Some commands to examine workspace, move around, etc:
>> who
Your variables are:
x y
who : lists the variables defined in workspace
>> whosName Size Bytes Class
x 3x1 24 double arrayy 3x2 48 double array
Grand total is 9 elements using 72 bytes
whos : lists names and basic properties of variables in the workspace
Entering Numeric Arrays>> a=[1 2;3 4]
a =
1 2
3 4
>> b = [2:-0.5:0]b =2 1.5 1 0.5 0
>> c = rand(2,4)c =0.9501 0.6068 0.8913 0.45650.2311 0.4860 0.7621 0.0185
Row separator:Semicolon (;) or newlineColumn separator:space or comma (,)
Use square brackets [ ]
Matrices must be rectangular. (Undefined elements set to zero)
Creating sequences using the colon operator (:)
Utility function for creating matrices.
Entering Numeric Arrays (Continued)
>> w = [-2.8, sqrt(-7), (3+5+6)*3/4]w =-2.8 0 + 2.6458i 10.5
>> m(3,2) = 3.5m = 0 00 00 3.5
>> w(2,5) = 23
w =-2.8 0 + 2.6458i 10.5 0 0
0 0 0 0 23
Using other MATLAB expressions
Matrix element assignment
Note: MATLAB deals with Imaginary numbers…
Adding to an existing array
Indexing into a Matrix in MATLAB
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
Rows (m) 3
4
5
Columns(n)
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A = A (2,4)
A (17)
Rectangular Matrix:
Scalar: 1-by-1 array
Vector: m-by-1 array1-by-n array
Matrix: m-by-n array
Array Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
3
4
5
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A =
A(3,1)A(3)
A(1:5,5)A(:,5) A(21:25)
A(4:5,2:3)A([9 14;10 15])
• Use () parentheses to specify index• colon operator (:) specifies range / ALL• [ ] to create matrix of index subscripts• 'end' specifies maximum index value
A(1:end,end) A(:,end)A(21:end)’
THE COLON OPERATOR
• Colon operator occurs in several forms– To indicate a range (as above)
– To indicate a range with non-unit increment
>> N = 5:10:35
N =
5 15 25 35
>> P = [1:3; 30:-10:10]
P =
1 2 3
30 20 10
• To extract ALL the elements of an array (extracts everything to a single column vector)
>> A = [1:3; 10:10:30;
100:100:300]
A =1 2 310 20 30100 200 300
>> A(:)ans =
110100220200330300
Numerical Array Concatenation [ ]
>> a=[1 2;3 4]
a =
1 2
3 4
>> cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a =
1 2 2 43 4 6 83 6 4 89 12 12 165 10 6 12
15 20 18 24
Use [ ] to combine existing arrays as matrix “elements”
Use square brackets [ ]
4*a
Row separator:semicolon (;)
Column separator:space / comma (,)
N.B. Matrices MUSTbe rectangular.
Matrix and Array Operators
Matrix Operators Array operators
() parentheses
' complex conjugate transpose
.' array transpose
^ power .^ array power
* multiplication .* array mult.
/ division ./ array division
\ left division
+ addition
- subtraction
>> help ops >> help matfun
Common Matrix Functionsinv matrix inverse
det determinant
rank matrix rank
eig eigenvectors and eigenvalues
svd singular value dec.
norm matrix / vector norm
• 1 & 2D arrays are treated as formal matrices– Matrix algebra works by default:
>> a=[1 2];>> b=[3
4];
>> a*bans =
11
>> b*aans =
3 64 8
1x2 row oriented array (vector)(Trailing semicolon suppresses display of output)
2x1 column oriented array
Result of matrix multiplication depends on order of terms (non-cummutative)
• Element-by-element (array) operation is forced by preceding operator with a period ‘.’
>> a=[1 2];>> b=[3
4];>> c=[3 4];
>> a.*b??? Error using ==> timesMatrix dimensions must agree.
>> a.*c
ans =3 8
Size and shape must match
>> w=[1 2;3 4] + 5
1 2 = + 5
3 4
1 2 5 5 = +
3 4 5 5
6 7=
8 9
Matrix Calculation-Scalar Expansion
>> w=[1 2;3 4] + 5w =
6 78 9
Scalar expansion
Matrix Multiplication
• Inner dimensions must be equal.
• Dimension of resulting matrix = outermost dimensions of multiplied matrices.
• Resulting elements = dot product of the rows of the 1st matrix with the columns of the 2nd matrix.
>> a = [1 2 3;4 5 6];
>> b = [3,1;2,4;-1,2];
>> c = a*b
c =
4 15 16 36
[2x3][3x2]
[2x3]*[3x2] [2x2]
a(2nd row).b(2nd column)
Array (element-by-element) Multiplication
• Matrices must have the same dimensions (size and shape)
• Dimensions of resulting matrix = dimensions of multiplied matrices
• Resulting elements = product of corresponding elements from the original matrices
• Same rules apply for other array operations
>> a = [1 2 3 4; 5 6 7 8];
>> b = [1:4; 1:4];
>> c = a.*b
c =
1 4 9 165 12 21 32 c(2,4) = a(2,4)*b(2,4)
>> a=[1 2]A =
1 2
>> b=[3 4];
>> a.*bans =
3 8
>> c=a+bc =
4 6
Matrix addition & subtraction operate element-by-element anyway. Dimensions of matrix must still match!
No trailing semicolon, immediate display of result
Element-by-element multiplication
>> A = [1:3;4:6;7:9]A =
1 2 34 5 67 8 9
>> mean(A)ans =
4 5 6
>> sum(A)ans =
12 15 18
>> mean(A(:))ans =
5
Many common functions operate on columns by default
Mean of each column in A
Mean of all elements in A
Clearing up
>> clear clear all workspace
>> clear VARNAME clear named variable
>> clear all clear everything(see help clear)
>> close all close all figures
>> clc clears command window display only
== is equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
~ not
& and
| or
isempty() true if matrix is empty, []
isfinite() true where elements are finite
isinf() true where elements are infinite
any() true if any element is non-zero
all() true is all elements are non-zero
zeros([m,n]) - create an m-by-n matrix of zeros
zeros(size(A)) - create a matrix of zeros the same size as A
Boolean (logical) operators
LOGICAL INDEXING
• Instead of indexing arrays directly, a logical mask can be used – an array of same size, but consisting of 1s and 0s (true and false) – usually derived as result of a logical expression.
>> X = [1:10]
X =
1 2 3 4 5 6 7 8 9 10
>> ii = X>6
ii =
0 0 0 0 0 0 1 1 1 1
>> X(ii)
ans =
7 8 9 10
• Logical indexing is a very powerful tool for selecting subsets of data. Combine multiple conditions using boolean operators.
>> >> x = [1:10];
>> y = x.^0.5;
>> i1 = x >= 5
I1 =
0 0 0 0 1 1 1 1 1 1
>> i2 = y<3
i2 =
1 1 1 1 1 1 1 1 0 0
>> ii = i1 & i2
ii =
0 0 0 0 1 1 1 1 0 0
>> find(ii)
ans =
5 6 7 8
Find function converts logical index to numeric index
>> plot(x,y,’bo’)
>> plot(x(ii),y(ii),’ro’)
Basic Plotting Commands
• figure : creates a new figure window• plot(x) : plots line graph of x vs index
number of array• plot(x,y) : plots line graph of x vs y• plot(x,y,'r--')
: plots x vs y with linetype specified in string : 'r' = red, 'g'=green, etcfor a limited set of basic colours.'−' solid line, '− −' dashed, 'o' circles…see graphics section of helpdesk
Simple Plotting>> x=[1:10]; y=x.^2;>> plot(x,y)
>> plot(x,y,'--')>> plot(x,y,‘r-')
>> plot(x,t,‘o')
Specify simple line types, colours, or symbols
Use the help command to get guidance on using another command or function
>> help plot
• By default any plotting command replaces any existing lines plotted in current figure.
• hold command ‘holds’ the current plotting axes so that subsequent plotting commands add to the existing figure instead of replacing content.
كارگاه آشنايي با نرم افزار متلب
گرافيك متلب
دكتر ايوب جعفري
GRAPHICS
• Basic Plotting– Linetypes, markers, colours, etc
• Subplots – creating multiple axes on a single figure
• Annotating figures – titles, labels, legends
• Editing figure properties
• Other plotting functions
Basic Plotting Commands
• figure : creates a new figure window• plot(x) : plots line graph of x vs index
number of array• plot(x,y) : plots line graph of x vs y• plot(x,y,'r--')
: plots x vs y with linetype specified in string : 'r' = red, 'g'=green, etc for a limited set of basic colours.
Plot(x,y,…properties)
• Plot(x,y,cml) – plot with a basic colour-marker-line combination (cml)– ‘ro-’, ‘g.-’, ‘cv--‘
– Basic colours : r, g, b, k, y, c, m– Basic markers : ‘o’, ‘v’, ‘^’, ’<‘, ’>’, ‘.’, ‘p’, ‘+’, ‘*’, ‘x’, ‘s’, ‘h’,
‘none’
– Linetypes : ‘-’, ’--‘, ‘-.’, ‘:’, ‘none’
• More detailed plot options can be specified through the use of property:value pairs– Plot(x,y,’o-’,’property’,value)
‘property’ is always a string naming the propery, value may be a number, array, or string, depending on the property type:
‘color’ : [R G B] - color (american spelling!) is specified with a [red green blue] value array, each in range 0-1.
[1 0 0] – pure red
[1 0. 0.5 0] – orange
– ‘linewidth’ : specified as a single number. Default = 0.5
– ‘linestyle’ : any of line type strings - ‘-’,’:’,etc
– ‘marker’ : any of marker strings – ‘v’, ’o’, etc
– ‘markersize’ : number, default = 6
– ‘markeredgecolor’ : color string ‘r’, ‘g’, or [R G B] value for the line defining edge of marker
– ‘markerfacecolor’ : color string or [R G B] for inside of marker (can be different from edge)
Can add any number of property:value pairs to a plot command:>> Plot(x,y,’prop1’,value1,’prop2’,value2,..)
Property Editor — Axis
Tree of objects
Edited objects
Help for object
GUI property browser & editorAccess from the figure’s view menu
Subplots• subplot(m,n,p) : create a subplot in an array of axes
>> subplot(2,3,1);
>> subplot(2,3,4);
m
n
P=1 P=2 P=3
P=4
Adding Text to Figures
• Basic axis labels and title can be added via convenient functions:>> xlabel('x-axis label text')>> ylabel('y-axis label text')>> title('title text')
• Legends for line or symbol types are added via the legend function:>> legend('line 1 caption','line 2 caption',…)
• Legend labels are given in the order lines were plotted
‘Handle’ Graphics
• MATLAB uses a hierarchical graphics model– Graphics objects organised according to their
dependencies: e.g. lines must be plotted on axes, axes must be positioned on figures
– Every object has a unique identifier, or handle• Handles are returned by the creating function
– ax = subplot(3,2,n)
– H = plot(x,y)
• Handles can be used to identify an object in order to inspect (get) or modify (set) its properties at any time
root
figure
axes UI-control UI-menu UI-contextmenu
line light image patch surface rectangle text
Object Hierarchy
The computer desktop
Figure window
Objects at any level are considered to be ‘children’ of their ‘parent’ object.
• Properties of an object with handle H, can be inspected/modified by:>> value = get(H,'propertyname')>> set(H,'propertyname',value)
• All property values echoed to screen by:>> get(H)
• 3 useful functions:– gcf : get current figure – returns handle of current figure– gca : get current axes – returns handle of current axes– gco : get current object – returns handle of current object
Can use these directly, instead of the handle
• Current object is last created (usually), or last object clicked on with mouse.
>> pp = get(gca,'position')pp =
0.1300 0.1100 0.7750 0.8150
>> set(gca,'position',pp+[0 0.1 0 -0.1])
The code above first gets the position of the current axes – location of bottom left corner (x0, y0), width (dx) and height (dy) (in normalised units) – then resets the position so that the axes sit 0.1 units higher on the page and decreases their height by 0.1 units.
Other plotting functions
• Matlab has many plotting functions – we will use a simple data set representing a surface to try these out.
• Enter the command peaks
z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ... - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ... - 1/3*exp(-(x+1).^2 - y.^2)
Peaks sets up a regular x and y grid, and defines the function z given above.
>> peaks;
Peaks is an example function, useful for demonstrating 3D data, contouring, etc. Figure above is its default output.P=peaks; - return data matrix for replotting…
>> P = peaks; - save output of peaks in P>> contour(P) - contour P using default contour values
x and y axes are simply the row and column numbers
>> contour(P,[-9:0.5:9]) – contour with specified contour values.
>> [C,h]=contour(P); - capture Contour value and handle>> clabel(C,h); - clabel function adds labels
>> [x,y,P] = peaks;>> contour(x,y,P,[-9:9])
x and y axes are true values
>> contourf(P,[-9:0.5:9]); - filled contour function>> colorbar - add colour scale
Pseudocolour plots
An alternative to contouring – provides a continuous colour-mapped 2D data field
• pcolor(Z) : plot pseudocolour plot of Z• pcolor(X,Y,Z) : plot of Z on grid X,Y
• shading faceted | flat | interp: set shading option
– faceted : show edge lines (default)– flat : don't show edge lines– interp : colour is linearly interpolated to give smooth
variation
>> pcolor(P) >> shading flat
>> shading interpData points are at vertices of grid, colourof facet indicates mean value of surrounding vertices. Colours are selected by interpolating data range into a colormap
>> pcolor(P);shading flat>> hold on>> contour(P,[1:9],'k')>> contour(P,[-9:-1],'k--')>> contour(P,[0 0],'k','linewidth',2)>> colorbar
colormaps
• Surfaces are coloured by scaling the data range to the current colormap. A colormap applies to a whole figure.
• Several predefined colormaps exist ('jet' (the default), 'warm','cool','copper','bone','hsv'). Select one with>> colormap mapname>> colormap('mapname')
• The current colormap can be retrieved with>> map=colormap
>> colormap cool
>> caxis([0 8]) - caxis function sets the [min max] limits of >> colorbar the colour scale. Need to refresh colourbar
• Colormaps are simply 3-column matrices of arbitrary length (default = 64 rows). Each row contains the [RED GREEN BLUE] components of the colour required, specified on a 0→1 scale.e.g.>> mymap = [ 0 0 0.1
0 0.1 0.20.1 0.2 0.3. . .. . . ]
>> colormap(mymap)
Specialized Plotting Routines
Specialized Plotting Routines (Continued)
Load jun07_all_5km_means.mat
Variables:
• mlat, mlon - latitude & longitude of measurements
• mT - mean air temperature
• msst - mean sea surface temperature
• mu, mv - mean wind components to east (x) and north (y)
• mws - mean wind speed
• Plot the different variables to get a feel for range of values and relationships between them.
• Plot positions of the points - geographical locations
>> load jun07_all_5km_means.mat>> whoYour variables are:mT mlat mlon msst mu mv
>> plot(mlon,mlat,'o‘)
>> plot(mlon,mlat,'o')>> hold on>> quiver(mlon,mlat,mu,mv)
Randomly distributed data can’t be used with contour, pcolor, surf, etc…data needs to be on a regular grid.
Use meshgrid to generate arrays of x and y on a regular grid.
[XX,YY] = meshgrid([-125.2:0.05:-124],[39.9:0.05:40.8]);
Use griddata to interpolate mu and mv onto the XX,YY grid … use system help to check usage
X-values required Y-values required
X and Y grids
>> [XX,YY] = meshgrid([-125.2:0.05:-124],[39.9:0.05:40.8]);>> gmws = griddata(mlon,mlat,mws,XX,YY);>> pcolor(XX,YY,gmws); shading flat; >> hbar = colorbar;>> hold on>> h1 = plot(mlon,mlat,'ko');
>> gu=griddata(mlon,mlat,mu,XX,YY);>> gv=griddata(mlon,mlat,mv,XX,YY);>> quiver(XX,YY,gu,gv,'k-');>> set(h1,'markeredgecolor','r','markersize',5)
>> set(gca,'linewidth',2,'fontweight','bold')>> xlabel('Longitude'); ylabel('latitude')>> set(hbar,'linewidth',2,'fontweight','bold')>> set(get(hbar,'xlabel'),'string','(m s^{-1})','fontweight','bold')>> xlabel('Longitude'); ylabel('latitude')>> title('CW96 : June 07 : 30m wind field')>> load mendocinopatch.mat>> patch(mendocinopatch(:,1),mendocinopatch(:,2),[0.9 0.9 0.9])
Printing
• From file menu:– ‘print’ to send to a printer
– Export to export to a file (gif, png, jpg, eps,…)
• Better to use command line> print filename.EXT -dEXT
File-type extension ‘png’, ‘ps’, ‘.eps’ appropriate to file type you want
Instruction to print engine to select file type (same format as a linux print destination)
> print myfigure.png -dpng
> print myfigure.png –dpng –r300
-rNNN option specifies print resolution to NNN dpi
• Common print file types– .ps - postscript (full page)
– .eps - encapsulated postscript (embeddable, infinitely scalable vector graphic – best for publication)
– .png - portable network graphic – best bitmap image option
– .jpg - JPEG image NEVER USE THIS!
.png .jpg
JPEG format is designed for photographic images with continuously varying tone. Hard edges suffer compression artefacts –distortions – ugly, and can make text impossible to read
.fig files
> hgsave(gcf,’filename.fig’)
Saves the current figure to a .fig file – this is a complete description of the figure as a set of matlab handle-graphics objects. Can reload the figure to make edits later
> hgload(‘filename.fig’)
كارگاه آشنايي با نرم افزار متلب
متلبتوابع و اسكريپت در
دكتر ايوب جعفري
Scripts
• Any set of Matlab commands saved to a (text) file with .m file extension
• Whole script can be run simply by entering the filename (without .m) on the command line
• Executes in the interactive workspace exactly as if you entered each line by line– Script can access existing variables
– Any variables created by script remain in workspace when it has finished running
figure
orient landscape
wysiwyg
clear all
load /worker/twelve/coastal_waves/jun07/data/section_jun07_3
sub1=subplot(2,2,1);
section_plot(gtheta,x,y,[],[],[],'x',[],'nonew');
extcontour(x(:,1),y,grhum,'label','color','w','fontsize',[9]);
txt=findobj(sub1,'type','text');
set(txt,'color','w')
xlimit=get(gca,'xlim');
ylimit=get(gca,'ylim');
aa=text([xlimit(1)],ylimit(2)+0.05*diff(ylimit),'a');
set(aa,'fontsize',[11],'fontweight','bold','color','k');
sub2=subplot(2,2,2);
section_plot(gmws,x,y,[],[],[0 30],'x',[],'nonew');
[xx,yy,gu]=reducegrid(x(:,1),y,gxuic,2,2);
[xx,yy,gv]=reducegrid(x(:,1),y,gxvic,2,2);
windvec(xx,yy,gu,gv,'screen','nonew','w');
xlimit=get(gca,'xlim');
ylimit=get(gca,'ylim');
bb=text([xlimit(1)],ylimit(2)+0.05*diff(ylimit),'b');
set(bb,'fontsize',[11],'fontweight','bold');
Example script: bams_fig8.m
Functions
• A MATLAB function is very similar to a script, but:– Starts with a function declaration linefunction [out1,out2]=function_name(in1)
– May have defined input arguments
– May have defined output arguments
– Executes in its own workspace: it CANNOT see, or modify variables in the calling workspace – values must be passed as input & output variables
function [s,c,t] = allTrig(x_deg)
% input angle in degrees
% output sin, cos, tan
x_rad = 2*pi*x_deg./360;
s = sin(x_rad);
c = cos(x_rad);
t = tan(x_rad);
Structure of a Function M-file
Keyword: function Function Name (same as file name .m)Output Argument(s) Input Argument(s)
Online Help
MATLABCode
• There are many functions built-in or supplied with MATLAB.– A few very basic functions are built in to the matlab
executable
– Very many more are supplied as m-files; the code can be viewed in command window by entering:>> type function_name
or in the editor by entering>> edit function_name
– Supplied m-files can be found, grouped by category, in $matlab_root_dir/toolbox/catagory
Workspaces or Stacks in MATLAB
• MATLAB (or base) workspace:For command line variables.
• Function workspaces:Each function has its own workspace for local variables.Communicate to function workspace via inputs and outputs.(Promotes structured coding and prevents name conflicts.)
• Global workspace:Global variables can be shared by multiple workspaces. (Must be initialized in all relevant workspaces.)
NOTE: Script files share the workspace of the function they are called from, or the base workspace if called from the command line.
Function Help
• MATLAB uses the ‘%’ character to start a comment – everything on line after ‘%’ is ignored
• A contiguous block of comment lines following the first comment, is treated as the ‘help’ text for the function. This block is echoed to screen when you enter
>> help function_name
This is very useful…use it when writing code!
>> help epot
MATLAB FUNCTION EPOTCalculates theta_e by Bolton's formula (Monthly Weather Review 1980 vol.108, 1046-1053)
usage: epot=epot(ta,dp,pr)
outputsepot : equivalent potential temperature (K)
inputs ta : air temp (K)dp : dew point (K)pr : static pressure (mb)
IM Brooks : july22 1994
e.g. help text from a function to calculate equivalent potential temperature
function epot=epot(ta,dp,pr)% MATLAB FUNCTION EPOT% Calculates theta_e by Bolton's formula (Monthly Weather % Review 1980 vol.108, 1046-1053)%% usage: epot=epot(ta,dp,pr)%% outputs% epot : equivalent potential temperature (K)% inputs ta : air temp (K)% dp : dew point (K)% pr : static pressure (mb)%% IM Brooks : july22 1994
% ensure temperatures are in kelvinta(ta<100)=ta(ta<100)+273.15;dp(dp<100)=dp(dp<100)+273.15;
% where dewpoint>temp, set dewpoint equal to tempdp(dp>ta)=ta(dp>ta);
% calculate water vapour pressure and mass mixing ratiomr=mmr(dp,pr);vap=vp(dp);
% calculate temperature at the lifing condensation levelTL=(2840./(3.5*log(ta) - log(vap) - 4.805))+55;
% calculate theta_eepot=ta.*((1000./pr).^(0.2854*(1-0.28E-3*mr))).* ...
exp((3.376./TL - 0.00254).*mr.*(1+0.81E-3*mr));
What it does
How it’s called
What input and outputs are (and units!)
Good coding practice, note what and why…you will forget
Editing codeCan use ANY ascii text editor
• Windows: Notepad
• Linux: vi, emacs, k-edit, kate,…
Matlab has a built in editor, to start it:
> edit
or to edit an existing code
> edit filename.m
Matlab editor will:
• Color-code text according to context/syntax
• Highlight incorrect syntax (errors)
• Highlight points where code could be more efficient
Line numbers(given by error messages)
Code optimisation
flag
Code state:green: perfectred: errorsorange: hints
Words highlighted blue are reserved words
The parts of a function
• Function declaration line (header)defines input & output variables
• Assignment statementsassign values to variables, modify values of existing variable
• Output statementsdisplay outputs: graphics, numeric values, write files…
• Programme flow-controldecision making (logic), loop control, iteration
Function declaration
[out1,out2]=afunction(in1,in2,in3,in4)
it is not necessary to use ALL of the output arguments (variables) when calling the function.
It is possible to write functions to handle variable numbers of inputs & outputs – e.g. use of optional inputs, or changing behaviour in response to number of outputs called.
You CANNOT use more inputs/outputs than defined in the function declaration.
Input variablesoutput variables
Handling optional input/output variables
• nargin – returns number of input arguments used in actual function call
• nargout – returns number of output arguments used in actual function callfunction [x,y]=myfunction(a,b,c)% …help text…
if nargin<3c=1;
end
…rest of code…
Set a default value if an input variable is not supplied
If, else, elseif
if conditionstatements;
elseif conditionstatements;
elsestatements;
end
Generic form:
if A<0disp(‘A is negative’)
elseif A>0disp(‘A is positive’)
elsedisp(‘A is neither’)
end
example
condition – a logical statement: evaluates to true (1) or false (0)statements – and other valid matlab statements
disp function displays a string in command window
if conditionstatements;
elsestatements;
end
if conditionstatements;
end
Don’t need all the parts of if/then/else
for loops
for n = firstn:dn:lastnstatements;
end
Generic form:
for n = 1:10x(n)=n^2;
end
example
N.B. loops are rather inefficient in MATLAB, the example above would execute much faster if vectorized as
>> x=[1:10].^2;
If you can vectorize code instead of using a loop, do so.
N.B. can specify non-integer values for nbut can only use integers as array indices
while loops
while conditionstatements;
end
Generic form:
n = 1;while n <= 10x(n)=n^2;n=n+1;
end
example
The statements within the while loop are executed repeatedly while the condition is true. Example does exactly the same as the for loop in previous example (another inefficient loop).
If the condition is false when first tested, the statements in the while loop will never be executed.
Initialise control variable before starting loop
Modify control variable within loop
while loops are often used where it is not known in advance how many iterations of the loop will be required
done = false;count = 0;while ~donecount = count + 1;lasta = a2;a2 = fix((B2-B1)/(PWR*da))*da;if abs(a2-lasta)<(3*da)done=1;
endend
The values of lasta and a2 change each time round the loop, iteration continues until the condition in if statement is true
Indent code within blocks – i.e. Between pairs of:• if...end• if...else...elseif...end
• while...end• for....end
Indent one level for EACH nested block of code.
Indenting makes it MUCH easier to read your code, and thus easier to debug.
Keeping code readable
Matlab stores arrays as contiguous blocks of memory. If an array grows inside a loop
e.g. for n=1:5000X(n) = n.^2;
end
Then matlab may have to keep moving the location of the variable in memory – repeatedly copying it – this slows down the code. If you know how big the variable needs to be, predefine it to pre-allocate the required block of memory.
A = [1:500000];x = zeros(size(A));for n = 1:length(A)x(n) = somefunction(A(n));
end
Pre-allocating arrays
Debugging code
If you have an error in your code, and error message will be displayed when it is run, e.g.
??? Error: File: quadplot.m Line: 14 Column: 23Unexpected MATLAB expression.
This (usually) gives a hint as to the type of error, and the location in the code. NB. Since matlab code is not compiled (in traditional sense) errors are identified ONLY when that line of code is run.
If you can’t figure out the problem just by examining the code…
...use interactive mode inside a function
• Add temporary statements to code to display information you need as it runs:
• Use the keyboard function– This halts execution of the function and returns
command to the keyboard/command window, but leaves you in the function’s workspace – can inspect variables, change values, etc. Enter returnto resume running the function
(N.B. if used inside a loop, control will be passed to keyboard on every iteration)
Setting breakpoints
• Matlab editor has a ‘debug’ menu– Set breakpoints to stop code at a particular point
and allow you to step through line by line
– Set conditional breakpoints that stop execution if a certain condition is met
– Set stop-on-error flag – code will stop and pass control to keyboard if an error or warning is encountered
(warnings are non-fatal errors, code will still run but is technically invalid, e.g. divide by zero)
ctrl-c
• If code is running much longer than seems reasonable – it may be stuck in an infinite loop– Condition for exiting a while loop never met
– Condition being tested in wrong place– Control variable ina for loop getting reset so its
maximum value is never reached
Can force code to stop with ctrl-c
Non-fatal errors
• Just because your code doesn’t have any syntax errors, and runs OK, doesn’t mean it does what you intended.
If the results you get don’t make sense, you probably have an error in the logic underlying your code…welcome to life as a programmer!
Strings
• MATLAB treats strings as arrays of characters– A 2D ‘string’ matrix must have the same number of
characters on each row!
>> name = [‘Ian’,’Brooks’]name =
IanBrooks
>> name=[‘Ian';‘Brooks']??? Error using ==> vertcatAll rows in the bracketed expression must have the same number of columns
>> name=[‘Ian ';‘Brooks']Name =
IanBrooks
• Can concatenate strings as:>> firstname = ‘Ian’;>> secondname = ‘Brooks’;>> fullname = [firstname,‘ ’,secondname]fullname =
Ian Brooks
• Strings defined within single quotation marks⇒ quotation mark within a string needs double quoting (2
single quotes)
>> thetitle = 'Ian Brooks’’s matlab class'thetitle =
Ian Brooks’s matlab class
String functions
• strcmp(str1,str2) - returns true (1) if str1 & str2 are equal
• findstr(S1,S2) - returns index to location of any occurrences of shorter string in longer
• strfind(text,pattern) - returns index to occurrences of pattern in text
See also…
• strncmp, strmatch,…helpdesk string functions section
• Break the job down into discrete parts – write the code to do each part
• For complex tasks start with a flow chart or algorithm
• COMMENT you code
• Use meaningful variable names –they can be as long as needed
• If part a section of code needs to run more than once…think about making it a separate function or sub-function
Good code management
• Keep code in one or more dedicated directories – separate from data
• Use meaningful function names
• Include a ‘help’ section of comments at the start of each function – include details of inputs/outputs and any options
• Beg/borrow/steal code from colleagues…don’t waste time reinventing something that’s already been done. Almost all programming is changing existing code, not writing new stuff! (honest!)
Good programming style
Save groups of related functions in their own directory…
- By application
- By project
Matlab will only find code that is:
• Part of core matlab installation
• In the current working directory
• On the search path
Can add directories to the path with the addpath command, e.g.:
> addpath d:\matlab\meteorology
startup.m file: if this file exists on the path, it will be run automatically at startup:
Windows network install:
M:\matlab – directory should be created when matlab first run. Put startup.m in here
LINUX
/home/USERNAME/matlab
Helping you stay organised
%-------------------------------------% Matlab startup file for IMB's laptop%-------------------------------------
%-- add paths for my m-files –addpath d:/matlab/aerosoladdpath d:/matlab/coastaladdpath d:/matlab/lidaraddpath d:/matlab/ndbcaddpath d:/matlab/pageaddpath d:/matlab/sectionsaddpath d:/matlab/sharemaddpath d:/matlab/sonicsaddpath d:/matlab/waveletaddpath d:/matlab/LEMaddpath d:/matlab/GPSbookaddpath d:/matlab/FAAMaddpath d:/matlab/FAAM/windsaddpath d:/matlab/faam/baeaddpath d:/matlab/TREXaddpath d:/matlab/SEASAWaddpath d:/matlab/SEASAW/turbulenceaddpath d:/matlab/SEASAW/SBWRaddpath d:/matlab/tethersondeaddpath d:/matlab/chilboltonaddpath d:/matlab/ASCOSaddpath d:/matlab/ASCOS/scratchaddpath d:/matlab/sodar
% COARE bulk flux algorithmaddpath d:/matlab/bulkflux/cor2.5addpath d:/matlab/bulkflux/cor2.6addpath d:/matlab/bulkflux/cor3.0addpath d:/matlab/bulkflux/gasflux/CO2addpath d:/matlab/bulkflux/gasflux/ozone
% netCDF Toolsaddpath d:/matlab/MEXCDF % my netCDF functionsaddpath d:/matlab/MEXCDF/mexncaddpath d:/matlab/MEXCDF/mexnc/testsaddpath d:/matlab/MEXCDF/snctoolsaddpath d:/matlab/MEXCDF/snctools/tests
%-- add path for generic data --addpath d:/matlab/coastlines % coastline data
%----------------------------------------------------------------------%-- set default figure options –set(0,'DefaultFigurePaperUnits','inches')
% v6 defaults to cm for EU countriesset(0,'DefaultFigureRenderer','painters')
% v7 default OpenGL causes problems
Put any code you ALWAYS want run into startup.mExample startup.m file (from my laptop)
كارگاه آشنايي با نرم افزار متلب
برنامه نويسي متلب
دكتر ايوب جعفري
Infinity & Not-a-Number (NaN)
Some operations return undefined values,• Division by zero returns Infinity (& a warning message)1/0ans = inf
• Division of zero by zero returns NaN1/0ans = NaN
• NaN does not plot – useful as a bad data marker.Data(iibad) = NaN sets points selected by
iibad = NaN
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Multidimensional Arrays
>> A = pascal(4);>> A(:,:,2) = magic(4)A(:,:,1) =
1 1 1 11 2 3 41 3 6 101 4 10 20
A(:,:,2) =16 2 3 135 11 10 89 7 6 124 14 15 1
>> A(:,:,9) = diag(ones(1,4));
Page N
Page 10 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
If we extract a slice from a 3D array: > slice = A(1,:,:)> size(slice)
ans =
1 4 9
Slice is STILL 3D, but one dimension is only 1 element deep. Can’t contour/pcolor plot because those function need a 2D array.
> slice = squeeze(slice);> size(slice)
ans =
4 9
squeeze function removes any dimensions that are just 1 deep
Squeeze
String to number:N = str2num([’34 35’]) N =
34 35
Number to string:tstr = [num2str(12),’:’,...
num2str(15),’:;,...num2str(34)]
tstr =
‘12:15:34’
String to number conversion (and back)
>> mystr = ‘The time is 12:30:15pm’
>> tempdata = str2num([mystr(13:14);mystr(16:17);mystr(19:20)])tempdata =
123015
>> tempdata = sscanf(mystr,'%*11c %d:%d:%d')tempdata =
123015
SAVING DATA• MATLAB uses its own platform-independent file format for
saving data – files have a .mat extension
– The save command saves variables from the workspace to a named file (or matlab.mat if no filename given)• save FILENAME – saves entire workspace to filename.mat
• save filename var1 var2 – saves named variables to filename.mat
– By default save overwrites an existing file of the same name, the –append switch forces appending data to an existing file (but variables of same name will be overwritten!)• save filename var1 var2 ... -append
– If a filename has spaces in it must be enclosed in quotessave ‘my long filename’ var1 var2 ...
– Can save a subset of variables matching distinct patternssave filename pattern1 pattern2 ...E.g. variables: x1 x2 x3 y1 y2 y3 z1 z2 z3
save all_x x* → saves x1 x2 x3
save all_ones *1 → saves x1 y1 z1
– save command has functional form where filename, variables, and options are passed as stringssave(‘my filename’,’var1’,’var2’)
Can use this form to pass filenames and variable names as string variables…useful to allow them to be defined interactively or by code rather than specified in advance.
myfilename = ‘my new filename’myvar = ‘var1’save(myfilename,var1)
Loading data
– Data is loaded back into workspace from a .mat file with the ‘load’ command
• load filename – loads entire .mat file• load filename var1 var2 …– loads named variables
– Again, a functional form of load command is available• load(filename,var1,var2,...)
– ASCII files can be loaded directly with –ascii option• load filename –ascii – loads contents of an ascii flatfile as
a variable called ‘filename’. The ascii file must contain a rectangular array of numbers so that it loads into a single matrix – no text headers.
• X=load(‘filename’,’-ascii’) – loads the ascii file into a variable ‘X’ – file must contain a simple 2D matrix of numbers only
Import & Export of Data
• Most of your data starts off outside matlab…you need to get it imported.
• Simple ascii files: > load file.txt –ascii
Import ‘Wizard’Start from ‘file’ menu
Allows selection & inspection of data being imported
ImportData function
Importdata: imports data from known common file formats, including Excel spreadsheets.
From Excel file, importdata will try and break down contents of a spreadsheet into consistent blocks of data (it won’t always work!)
> temp = importdata(files(n).name)temp =
data: [1x1 struct]textdata: [1x1 struct]
colheaders: [1x1 struct]
> temp.dataans =
Sheet1: [27x7 double]
Importdata returns a data structure
• Low-level file input and output is very similar to that in 'C', but with inherent vectorization.
• Files are opened with> fid = fopen(filename)> fid = fopen(filename,mode)
• fid is a file identifier, used as a reference to the file for all subsequent read and write operations
• Files are closed with:
> fclose(fid)
fopen modes'r' Open file for reading (default).'w' Open file, or create new file, for writing; discard
existing contents, if any.'a' Open file, or create new file, for writing; append
data to the end of the file.'r+' Open file for reading and writing.'w+' Open file, or create new file, for reading and
writing; discard existing contents, if any.'a+' Open file, or create new file, for reading and
writing; append data to the end of the file.'A' Append without automatic flushing; used with tape
drives.'W' Write without automatic flushing; used with tape
drives.
Reading & Writing Formatted Ascii Data
To write formatted data:> count = fprintf(fid,format,data,...)
To read formatted ascii data:> data = fscanf(fid,format)> [A,count] = fscanf(fid,format,size)
format is a string specifying the ascii data format, same as used in ‘C’ fscanf differs from its ‘C’ equivalent in that it is vectorized – multiple reads of format string carried out until end of file is reached, or matrix size is reached.
Format strings
• The format string consists of ordinary characters, and/or conversion specifications indicating data type:
%12e
Initial % character
Field width
Conversion character
%c Sequence of characters; number specified by field width
%d Base 10 integers%e, %f, %g Floating-point numbers%i Defaults to base 10 integers. Data starting
with 0 is read as base 8. Data starting with 0x or 0X is read as base 16.
%o Signed octal integer%s A series of non-white-space characters%u Signed decimal integer%x Signed hexadecimal integer[...] Sequence of characters (scanlist)
Add one or more of these characters between the % and the conversion character:
An asterisk (*) Skip over the matched value. If %*d, then the value that matches d is ignored and is not stored.
A digit string Maximum field width. For example, %10d.A letter The size of the receiving object, for example,
h for short, as in %hd for a short integerl for long, as in %ld for a long integer, or
%lg for a double floating-point number.
2010/12/01 1 1.42010/12/02 2 2.12010/12/03 3 1.82010/12/04 4 2.1
Data provided in ASCII files usually has a form that is easy for people to read, but complicated for a computer to read in, e.g.:
> fd = fopen(‘myfile.txt’)> data = fscanf(fd,’%4d/%2d/%2d %d %f’,[5 4])data =
1.0e+003 *
2.0100 2.0100 2.0100 2.01000.0120 0.0120 0.0120 0.01200.0010 0.0020 0.0030 0.00400.0010 0.0020 0.0030 0.00400.0014 0.0021 0.0018 0.0021
> fclose(fd)
> fd = fopen(‘myfile.txt’)> data = fscanf(fd,’%4d/%2d/%2d %d %f’,[5 4])’
data =
1.0e+003 *
2.0100 0.0120 0.0010 0.0010 0.00142.0100 0.0120 0.0020 0.0020 0.00212.0100 0.0120 0.0030 0.0030 0.00182.0100 0.0120 0.0040 0.0040 0.0021
> fclose(fd)
Transpose operator to flip rows/columns in output
Reading whole lines
> tline = fgetl(fid)
reads the next whole line of text from fid, returning it without the line termination character.
> tline = fgets(fid)
reads the next line of text, including line termination character.
> tline = fgets(fid,nchar)
reads nchar characters from the next line of fid, next read will start on next line.
Binary number representation
‘uchar’ – 8-but unsigned interger (1 byte): 0-255simple binary number
0 0 0 0 0 0 0 0 = 0
128 64 32 16 8 4 2 1
0 0 0 1 0 1 0 1 = 21
1 0 1 0 0 0 0 1 = 161
1 1 1 1 1 1 1 1 = 255
schar = signed (+ve and –ve) 8-bit integers : -127:127
still only 1 byte, but 1 bit now used to indicate sign. ALL computers use an encoding called 2’s complement.To represent a –ve number:
- encode magnitude in binary
- invert digits
- add 1
0 0 0 0 1 0 0 1-9 =
+/- 64 32 16 8 4 2 1
1 1 1 1 0 1 1 0
invert
and +1
1 1 1 1 0 1 1 1
A 1 in first place -> number is negative, to recover value invert digits and add 1
0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 1 = -9
Numbers are ALWAYS encoded as integer numbers of bytes (N × 8-bits)
Different machine architectures (PC, unix, CRAY, VMS,…) use different encodings.
BYTE ORDER:Big-endian – most significant byte first
Little-endian – least significant byte first
Floating point numbers:
• One bit encodes sign
• A group of bits encodes an integer representation of magnitude
• A smaller group of bits encodes the exponent
in base 10: 3.142 = 3142×10-3
You don’t need to know the details of the encoding used…you do need to know which one to specify.
Larger numbers & decimals
Reading Binary Data>> data = fread(fid)>> data = fread(fid,count,precision,skip,format)
NB. All input parameters except fid are optional.
count may take the forms:
n : read n values into a column array
inf : read to end of file, data is a column array
[m,n] : read enough data to fill a matrix of size [m,n], matrix is filled in column order, and padded with zeros if insufficient data to fill it. m must be a positive integer, n may be inf – read to end of file, data has m rows, and however many columns are required.
'cray' or 'c' Cray floating point with big-endian byte ordering
'ieee-be' or 'b' IEEE floating point with big-endian byte ordering
'ieee-le' or 'l' IEEE floating point with little-endian byte ordering
'ieee-be.l64' or 's' IEEE floating point with big-endian byte ordering and 64-bit long data type
'ieee-le.l64' or 'a' IEEE floating point with little-endian byte ordering and 64-bit long data type
'native' or 'n' Numeric format of the machine on which MATLAB is running (the default)
'vaxd' or 'd' VAX D floating point and VAX ordering
'vaxg' or 'g' VAX G floating point and VAX ordering
> fopen(filename,mode,format)> data = fread(fid,count,precision,skip,format)
Opens a binary file and treats all data read or written as being of the specified format. This may be necessary to read binary files written under a different operating system.
FORMATS
valid precisions
MATLAB C or Fortran Interpretation
'schar' 'signed char' Signed character; 8 bits'uchar' 'unsigned char' Unsigned character; 8 bits'int8' 'integer*1' Integer; 8 bits'int16' 'integer*2' Integer; 16 bits'int32' 'integer*4' Integer; 32 bits'int64' 'integer*8' Integer; 64 bits'uint8' 'integer*1' Unsigned integer; 8 bits'uint16' 'integer*2' Unsigned integer; 16 bits'uint32' 'integer*4' Unsigned integer; 32 bits'uint64' 'integer*8' Unsigned integer; 64 bits'float32' 'real*4' Floating-point; 32 bits'float64' 'real*8' Floating-point; 64 bits'double' 'real*8' Floating-point; 64 bits
Writing Binary Data
>> count = fwrite(fid,data,precision)>> count = fwrite(fid,data,precision,skip)
• Data is a single matrix and is written to the file in column order.
• Count is the number of values successfully written.
Working with dates and times can be problematic – we often want year, month, day, hour, minute, second –but manipulating them is tricky.
Serial times (e.g. Julian Day) simplify manipulation of date and time, but need conversion between serial time and ‘broken down’ time bits.
Serial times have a simple incrementing unit of time (seconds, days…) and a fixed reference time. E.g., Julian day is a day of year – only useful within a single year.
Matlab serial time is a serial day, with a reference (start) date (day 0) of:
00:00:00 January 1st 0000AD
A whole set of functions is provided to convert back and forth between Matlab serial time & year, month, day, etc.
Matlab knows leap years etc, so don’t need to worry about accounting for them yourself.
Time
now return serialtime now.
datevec(T) return vector of time components for serial time T:[YY, MM, DD, hh, mm, ss]
Try running now, and datevec(now)
datenum(Tvec)
return serial time for the date vector Tvec, e.g.
datenum([2009,12,9,15,30,00])ans =
7.3412e+005
datestr(T,format)
returns a formatted date/time string given serial time(s) T. ‘format’ can be a number –specifying one of 31 predefined formats – or a format string specifing a custom format (See matlab HELP)
One problem with use of a serial day is that for short time intervals, the fraction-of-day may be not be exactly represented (rounding errors of binary representation)…can lead to problems trying to match times from 2 separate time series.
Keep going…
• You cannot be taught to program, you can only learn by doing it.
• Use the help system…it has (almost) all the answers
• Library has > 150 books on Matlab, from beginners guides to very specialised applications
• Practice – use Matlab for anything and everything, it will be slow at first, but you will learn.
كارگاه آشنايي با نرم افزار
SPSSدكتر ايوب جعفري
Object of the Course
• About the four-windows in SPSS
• The basics of managing data files
• The basic analysis in SPSS
Introduction: What is SPSS?
• Originally it is an acronym of Statistical Package for the Social Science but now it stands for Statistical Product and Service Solutions
• One of the most popular statistical packages which can perform highly complex data manipulation and analysis with simple instructions
The Four Windows:Data editorOutput viewerSyntax editorScript window
The Four Windows: Data Editor
• Data EditorSpreadsheet-like system for defining, entering, editing, and displaying data. Extension of the saved file will be “sav.”
The Four Windows: Output Viewer
• Output ViewerDisplays output and errors. Extension of the saved file will be “spv.”
The Four Windows: Syntax editor
• Syntax EditorText editor for syntax composition. Extension of the saved file will be “sps.”
The Four Windows: Script Window
• Script WindowProvides the opportunity to write full-blown programs, in a BASIC-like language. Text editor for syntax composition. Extension of the saved file will be “sbs.”
The basics of managing data files
Opening SPSS• Start → All Programs → SPSS Inc→ SPSS 16.0 →
SPSS 16.0
Opening SPSS
• The default window will have the data editor• There are two sheets in the window:
1. Data view 2. Variable view
Data View window
• The Data View windowThis sheet is visible when you first open the Data Editor and this sheet contains the data
• Click on the tab labeled Variable View
Click
Variable View window
• This sheet contains information about the data set that is stored with the dataset
• Name– The first character of the variable name must be alphabetic– Variable names must be unique, and have to be less than 64
characters. – Spaces are NOT allowed.
Variable View window: Type
• Type– Click on the ‘type’ box. The two basic types of variables
that you will use are numeric and string. This column enables you to specify the type of variable.
Variable View window: Width
• Width– Width allows you to determine the number of
characters SPSS will allow to be entered for the variable
Variable View window: Decimals• Decimals
– Number of decimals– It has to be less than or equal to 16
3.14159265
Variable View window: Label
• Label– You can specify the details of the variable– You can write characters with spaces up to 256
characters
Variable View window: Values• Values
– This is used and to suggest which numbers represent which categories when the variable represents a category
Defining the value labels
• Click the cell in the values column as shown below• For the value, and the label, you can put up to 60
characters.• After defining the values click add and then click OK.
Click
Practice 1• How would you put the following information into SPSS?
Value = 1 represents Male and Value = 2 represents Female
Name Gender HeightJAUNITA 2 5.4SALLY 2 5.3DONNA 2 5.6SABRINA 2 5.7JOHN 1 5.7MARK 1 6ERIC 1 6.4BRUCE 1 5.9
Practice 1 (Solution Sample)
Click
Click
Saving the data
• To save the data file you created simply click ‘file’ and click ‘save as.’ You can save the file in different forms by clicking “Save as type.”
Click
Sorting the data
• Click ‘Data’ and then click Sort Cases
Sorting the data (cont’d)• Double Click ‘Name of the students.’ Then click
ok.
Click
Click
Practice 2
• How would you sort the data by the ‘Height’ of students in descending order?
• Answer– Click data, sort cases, double click ‘height of
students,’ click ‘descending,’ and finally click ok.
Transforming data
• Click ‘Transform’ and then click ‘Compute Variable…’
Transforming data (cont’d)
• Example: Adding a new variable named ‘lnheight’ which is the natural log of height – Type in lnheight in the ‘Target Variable’ box. Then type in
‘ln(height)’ in the ‘Numeric Expression’ box. Click OK
Click
Transforming data (cont’d)
• A new variable ‘lnheight’ is added to the table
Practice 3• Create a new variable named “sqrtheight”
which is the square root of height.• Answer
The basic analysis
The basic analysis of SPSS that will be introduced in this class • Frequencies
– This analysis produces frequency tables showing frequency counts and percentages of the values of individual variables.
• Descriptives– This analysis shows the maximum, minimum,
mean, and standard deviation of the variables
• Linear regression analysis– Linear Regression estimates the coefficients of
the linear equation
Opening the sample data
• Open ‘Employee data.sav’ from the SPSS– Go to “File,” “Open,” and Click Data
Opening the sample data• Go to Program Files,” “SPSSInc,” “SPSS16,” and
“Samples” folder.• Open “Employee Data.sav” file
Frequencies
• Click ‘Analyze,’ ‘Descriptive statistics,’ then click ‘Frequencies’
Frequencies
• Click gender and put it into the variable box.• Click ‘Charts.’ • Then click ‘Bar charts’ and click ‘Continue.’
Click Click
Frequencies
• Finally Click OK in the Frequencies box.
Click
Using the Syntax editor• Click ‘Analyze,’ ‘Descriptive statistics,’ then
click ‘Frequencies.’• Put ‘Gender’ in the Variable(s) box.• Then click ‘Charts,’ ‘Bar charts,’ and click
‘Continue.’• Click ‘Paste.’
Click
Using the Syntax editor
• Highlight the commands in the Syntax editor and then click the run icon.
• You can do the same thing by right clicking the highlighted area and then by clicking ‘Run Current’
ClickRight Click!
Practice 4
• Do a frequency analysis on the variable “minority”
• Create pie charts for it
• Do the same analysis using the syntax editor
Answer
Click
Descriptives
• Click ‘Analyze,’ ‘Descriptive statistics,’ then click ‘Descriptives…’
• Click ‘Educational level’ and ‘Beginning Salary,’ and put it into the variable box.
• Click Options
Click
Descriptives
• The options allows you to analyze other descriptive statistics besides the mean and Std.
• Click ‘variance’ and ‘kurtosis’• Finally click ‘Continue’
Click
Click
Descriptives
• Finally Click OK in the Descriptives box. You will be able to see the result of the analysis.
Regression Analysis
• Click ‘Analyze,’ ‘Regression,’ then click ‘Linear’ from the main menu.
Regression Analysis
• For example let’s analyze the model • Put ‘Beginning Salary’ as Dependent and ‘Educational Level’ as
Independent.
εββ ++= edusalbegin 10
ClickClick
Regression Analysis
• Clicking OK gives the result
Plotting the regression line• Click ‘Graphs,’ ‘Legacy Dialogs,’
‘Interactive,’ and ‘Scatterplot’ from the main menu.
Plotting the regression line• Drag ‘Current Salary’ into the vertical axis box
and ‘Beginning Salary’ in the horizontal axis box.• Click ‘Fit’ bar. Make sure the Method is
regression in the Fit box. Then click ‘OK’.
ClickSet this to Regression!
Practice 5
• Find out whether or not the previous experience of workers has any affect on their beginning salary? – Take the variable “salbegin,” and
“prevexp” as dependent and independent variables respectively.
• Plot the regression line for the above analysis using the “scatter plot” menu.
Answer
Click
Click on the “fit” tab to make sure the method is regression