Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University Jan 25,2012.

Slides:



Advertisements
Similar presentations
MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
Advertisements

StatLab Workshop Yale University Maximiliano Appendino, Economics October 18 th, 2013.
Introduction to MATLAB The language of Technical Computing.
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
MATLAB MATLAB is a high-level technical computing language and
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to MATLAB Week 13 – 4/21/09. Instructor: Kate Musgrave Time: Tuesdays 3-5pm Office Hours: Tuesdays 1:30-3pm
Introduction to MATLAB 7 for Engineers
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/22/2003.
Digital Image Processing Lecture3: Introduction to MATLAB.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
MATLAB Lecture One Monday 4 July Matlab Melvyn Sim Department of Decision Sciences NUS Business School
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to MATLAB Session 1 Prepared By: Dina El Kholy Ahmed Dalal Statistics Course – Biomedical Department -year 3.
Introduction to M ATLAB EE 100 – EE Dept. - JUST.
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Lecture 4 MATLAB Windows Arithmetic Operators Maintenance Functions
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
INTRODUCTION TO MATLAB LAB# 01
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
Chapter 1: Getting Started with MATLAB MATLAB for Scientist and Engineers Using Symbolic Toolbox.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Basics of MATLAB By DR. Wafaa Shabana
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
OUTLINE Overview Numbers, variables and similar in Matlab
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Introduction to Matlab By E. Noura Semary. Contents MATLAB Environment  Command window, Workspace, Path window, Editor window,and Figure window) Basic.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
BOĞAZİÇİ UNIVERSITY DEPARTMENT OF MANAGEMENT INFORMATION SYSTEMS MATLAB AS A DATA MINING ENVIRONMENT.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
ECE 351 M ATLAB I NTRODUCTION ( BY T EACHING A SSISTANTS )
Introduction to Matlab Patrice Koehl Department of Biological Sciences National University of Singapore
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
An Introduction to Programming in Matlab Emily Blumenthal
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Matlab Programming for Engineers
ECE 1304 Introduction to Electrical and Computer Engineering
Computer Application in Engineering Design
Introduction to Matlab
Lecture: MATLAB Chapter 1 Introduction
2) Platform independent 3) Predefined functions
Introduction to MATLAB
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
Lecture 3 MATLAB programming (1)
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Lecture 2 Introduction to MATLAB
Digital Image Processing
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Matlab Basic Dr. Imtiaz Hussain
Experiment No. (1) - an introduction to MATLAB
Matlab Basics.
Write the date in English
Presentation transcript:

Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University Jan 25,2012

References Product help (F1) ademia/student_center/tutori als/launchpad.html

Main content I.introduction II.syntax and command III.M-file programming IV.Advanced programming

Chap1. introduction 1.1 Matlab 's history 1.2 Main features of Matlab 1.3 Programming environment 1.4 Matlab Desktop (V2011b)

1.1 Matlab 's history MATLAB = MATrix (Matrices) & LABoratory

1.1 Matlab 's history  December 1996 First printing For MATLAB 5  May 1997 Second printing For MATLAB 5.1  September 1998 Third printing For MATLAB 5.3  September 2000 Fourth printing Revised for MATLAB 6 (Release 12)  June 2001 Online only Revised for MATLAB 6.1 (Release 12.1)  July 2002 Online only Revised for MATLAB 6.5 (Release 13)  August 2002 Fifth printing Revised for MATLAB 6.5  June 2004 Sixth printing Revised for MATLAB 7.0 (Release 14)  October 2004 Online only Revised for MATLAB (Release 14SP1)  March 2005 Online only Revised for MATLAB (Release 14SP2)  June 2005 Seventh printing Minor revision for MATLAB (Release 14SP2)  September 2005 Online only Minor revision for MATLAB 7.1 (Release 14SP3)  March 2006 Online only Minor revision for MATLAB 7.2 (Release 2006a)  September 2006 Eighth printing Minor revision for MATLAB 7.3 (Release 2006b)  March 2007 Ninth printing Minor revision for MATLAB 7.4 (Release 2007a)  September 2007 Tenth printing Minor revision for MATLAB 7.5 (Release 2007b)  March 2008 Eleventh printing Minor revision for MATLAB 7.6 (Release 2008a)  October 2008 Twelfth printing Minor revision for MATLAB 7.7 (Release 2008b)  March 2009 Thirteenth printing Minor revision for MATLAB 7.8 (Release 2009a)  September 2009 Fourteenth printing Minor revision for MATLAB 7.9 (Release 2009b)  March 2010 Fifteenth printing Minor revision for MATLAB 7.10 (Release 2010a)  September 2010 Sixteenth printing Revised for MATLAB 7.11 (R2010b)  April 2011 Online only Revised for MATLAB 7.12 (R2011a)  September 2011 Seventeenth printingRevised for MATLAB 7.13 (R2011b)

1.2 Main features of Matlab  High-level language for technical computing  Development environment for managing code, files, and data  Interactive tools for iterative exploration, design, and problem solving  Mathematical functions for linear algebra, statistics, Fourier analysis,  filtering, optimization, and numerical integration  2-D and 3-D graphics functions for visualizing data  Tools for building custom graphical user interfaces  Functions for integrating MATLAB based algorithms with external applications and languages, such as C, C++, Fortran, Java™, COM, and Microsoft® Excel®

8 1.3 Programming environment  Core functionality as compiled C-code, m-files  Additional functionality in Toolboxes (m-files)  Interactive operation

Start matlab and see(demo) 1.4 Matlab Desktop (V2011b)

Command History: View, search, copy, or execute statements you previously entered in the Command Window Command Window: Run MATLAB language statements. Current Folder Browser: Vinew, open, and find files and file content. Perform file management operations. Editor: Create, edit, debug, and analyze files containing MATLAB language statements. Figures: Create, modify, view, and print figures generated with MATLAB. Comparison Tool: View line-by-line differences between two files. Help Browser: View and search the documentation and demos for all your MathWorks products. Profiler: Improve the performance of your MATLAB code. Variable Editor: View array contents in a table format and edit the values. Web Browser: View HTML and related files produced by MATLAB. Workspace Browser: View and change the contents of the workspace.

Chap2. syntax and command 2.1 Basic concept 2.2 Matrices & Arrays 2.3 Commonly used commands 2.4 Flow control 2.5 Graphics

2.1 Basic concept 1.Identifier Name of functions or variables. Require Composed by letter, numerical and underline; Not more than 31 characters; Case sensitivity; Can not start by numerical; Example A , b, c8, d_f 2g, h(k

2.1 Basic concept 2. Constant pi iImaginary unit jSame as i epsFloating-point relative precision RealminSmallest floating-point number RealmaxLargest floating-point number InfInfinity NaNNot-a-number

2.1 Basic concept 3.Variable Just for storage the data. 4.Functions Usually: the name of function is composed by small letters.

2.1 Basic concept 5. Order of identifier Searches a. variable in current workspace b. built-in variable c. built-in m-file d. m-file in current directory e. m-file on search path

2.1 Basic concept 6. Operators + - * / …… Relational operators ==(equal to)~= (not equal) (greater than)>= (greater than or equal to) Logical operators &(and) |(or) ~(not)

2.1 Basic concept 7. Expression Variables, constants and functions connected by the operator. a+b c*f(a)

2.1 Basic concept 8. Statement Value of the expression assigned to a variable called assign command statement; = a = zeros(2,2);

2.1 Basic concept 9. Comment & others % ; …

2.2 Matrices & Arrays 1.Matrices generate Colon(:) & Brackets([]) ones, zeros, sparse magic, randn linspace,logspace true,false

2.2 Matrices & Arrays 1.Matrices generate Colon(:) Brackets([]) a = [1,2,3;4,5,6;7,8,9] b = 1:2:10

2.2 Matrices & Arrays 2.Operators +Addition -Subtraction *Matrices Multiplication /Matrices Division \Matrices Left division ^Matrices Power 'Complex conjugate transpose ( )Specify evaluation order

2.2 Matrices & Arrays.* Element-by-element multiplication./ Element-by-element division.\ Element-by-element left division.^ Element-by-element power.' Unconjugated array transpose

2.2 Matrices & Arrays size,length isempty,any,all diag, triu, tril inv,det,svd, …… 3. Other operate

2.2 Matrices & Arrays 4.Example A=magic(3) X=[1 3 5]' b=A*X

2.3 Commonly used commands 1.help, lookfor 2.Who,whos,disp 3.Save,load 4.clc, clear 5.cd,dir,pwd,path,!(system) 6.input,ginput

2.4 Flow control 1.Conditional Control if, else, switch % Generate a random number a = randi(100, 1); % If it is even, divide by 2 if rem(a, 2) == 0 disp('a is even') b = a/2; end

2.4 Flow control 1.Conditional Control if, else, switch a = randi(100, 1); if a < 30 disp('small') elseif a < 80 disp('medium') else disp('large') end

2.4 Flow control 1.Conditional Control if, else, switch [dayNum, dayString] = weekday(date, 'long', 'en_US'); witch dayString case 'Monday' disp('Start of the work week') case 'Tuesday' disp('Day 2') case 'Wednesday' disp('Day 3') case 'Thursday' disp('Day 4') case 'Friday' disp('Last day of the work week') otherwise disp('Weekend!') end

2.4 Flow control 2.loop Control— for,while,continue, break for n = 1:9 for m=1:n r(n,m)=m*n; end if n>5, continue; end end r

2.4 Flow control 2.loop Control— for,while,continue, break f(1)=1; f(2)=1; n=1; while f(n)+f(n+1)<30 f(n+2)=f(n)+f(n+1); n=n+1; end f fibnacci

2.4 Flow control 3.error Control— try,throw catch try statement... statement catch exceptObj statement... statement end

2.4 Flow control 3.error Control— try,throw,catch try statement … statement catch err statement... statement end

clear a=magic(4); b=eye(3); try c = a * b; [na,ma]=size(a); [nb,mb]=size(b); if (ma~=nb) error('afdas'); err = MException('whj:NotMatch','A=(%d,%d),B=(%d,%d)',na,ma,nb,mb); throw(err); end catch err c=a(1:3,1:3)*b if (strcmp(err.identifier,'whj:NotMatch')) err else rethrow(err); end

exception = MException(msgIdent, msgString, v1, v2,...) exception = MException('AcctError:Incomplete',... 'Field ''%s.%s'' is not defined.',... 'Accounts', 'ClientName'); exception.message ans = Field 'Accounts.ClientName' is not defined.

2.5 Graphics 1. 2D Graphics plot, plotyy, subplot, loglog, semilogx,semilogy hist,histc,staris  area, fill, pie, bar,barh, stem, errorbar, polar,rose, fplot,ezplot  scatter, Image,imagesc, pcolor,imshow

2.5 Graphics 2. Figure tool grid on, grid off title, xlabel, ylabel, zlabel, text axis ij, axis equal close

2.5 Graphics 3. 3D Graphics  plot3,pie3  mesh,meshc,meshz  surf,waterfall,surfc  contour,quiver,fill3  tem3,slice,scatter3 2D graphs:  3D graphs:

2.5 Graphics 3. 3D Graphics Dis3D_topo_demo 2D graphs:  3D graphs:

2.5 Graphics 4. Others plot Plot catalog select a variable from the workspace and see the graphics menu …

Chap3. M-file programming 3.1 Scripts m-file 3.2 function m-file 3.3 Function calls and parameter passing 3.4 Debug m-file

Scripts m-file 1. Just only composed by a bunch of instruction set (including the control flow of instructions including )

3.1 Scripts m-file 2. Variable storaged in the base workspace shared with the command window.

3.1 Scripts m-file 3. Example %circle.m clf; r=2; t=0:pi/100:2*pi; x=r*exp(i*t); plot(x,'r*'); axis('square');

3.2 function m-file 1. Just only add a function declare line in the scripts m-file. function y = mean(x) % claculate the mean value % for vecter, mean(x) return the mean value % for matrices, MEAN(x) is a vecter, each element is the mean value of the Column vecter of matrces. % whi, 1/25/2012 [m,n]=size(x); if m==1 m=n; end y=sum(x)/m;

function m-file 2. Variable storaged in the function workspace separated with the command window.

function m-file 3. Primary and Subfunctions funciton a = prifun(x) ….. r=3; a = 2 + subfun(r); function b = subfun(r) …

function m-file 4. style Declare function line %Comment line %Help online zone (lookfor 、 help) %Edit record and copyright infomation Function body

Function calls and parameter passing 1. Local and global variable K = 1; ki = 105; f = anim(K,ki); image(f.cdata);

Function calls and parameter passing 2. Functions calls [out1,out2,~,out3] = fun(in1,in2,…); function [y1,y2,y3] = fun1(x1,x2,x3) % demo functions calls % x1,x2,x3: input argument parameters % y1,y2,y3: output argument parameters %{ [y1,~,y3] = fun1(1,2,4); %} % whj,1/25/2012 y1 = x1+x2; y2 = x2+x3; y3 = x3+x1;

Function calls and parameter passing 3. Parameter passing with adjustable parameters K = 1; ki = 105; f = anim(K,ki); image(f.cdata);

Function calls and parameter passing 3. Parameter passing with adjustable parameters argin argout

Function calls and parameter passing 4. Pass across the space variable x= evalin(‘base’, ‘K’)

Debug m-file 1. Two type errors Syntax variable name error … Run-time Algorithm error

Debug m-file 2. Using debug tools

Debug tool

 Debug menu Continue :恢复程序运行至结束或另一个断点 。 Single Step :单步执行函数。 Step In :深入下层局部工作区 。 Quit Debugging :退出调试状态。 Set/Clear Breakpoint :设置 / 清除光标处的断点 。 Clear All Breakpoints :清除程序中的所有断点 。 Stop if Error :运行至出错或结束。 Stop if Warning :运行至警告消息或结束。 Stop if NaN of Inf :运行至运算结果出现 NaN 或 Inf 。

Chap4. Advanced programming 4.1 File Operate 4.2 Graphice User Interface(GUI) 4.3 Application Programming Interface(API) 4.4 complier

File Operate 1.fopen,fclose 2.fread,fwirte 3.xlsread,xlswrite 4.getline 5.Fprintf

浙江大学地球科学系 王华军 60 ( 1 ) open &close fid=fopen(‘datafile’ , ‘r’) ‘r’ —— read ‘w’ —— write ‘a’ —— add ‘rt’ —— read &write

61 ( 1 ) open &close fclose(fid) close fid fclose(all) close all

浙江大学地球科学系 王华军 62 ( 1 ) open &close For spacial *.mat save load

63 ( 2 ) read &write fread fwrite

浙江大学地球科学系 王华军 64 ( 2 ) Example(Binary) %write a=1:50; fid=fopen('user.dat', 'w'); fwrite(fid,a); fclose(fid);

%read fid=fopen('user.dat','r'); a=fread(fid,50); fclose(fid); (2) Example(Binary)

(3) Examples 1.(newful) mrrDpro.m 2.(newfel) 2D visulization 3. actic em31 figure 4. 3dVisualize

Graphice User Interface(GUI)

 MATLAB 能够以比较简单的方式实现一系列的图形界面功能。通过对控 件、菜单属性的设置和 Callback 的编写,就能够满足大多数用户的需求。  控件的 Callback 属性: Callback 属性的取值是字符串,可以是某个 M 文件名或一小段 MATLAB 语句。当用户激活控件对象(例如 :在控件对 象图标上单击鼠标左键 )时,应用程序就运行 Callback 属性定义的子程 序。 控件的 Callback 属性  菜单的 Callback 属性: Callback 属性的取值是字符串,可以是某个 M 文件名或一小段 MATLAB 语句。当用户激活菜单对象时,若没有子菜单 就运行 Callback 属性定义的子程序。若有,先运行 Callback 属性定义的 子程序,再显示子菜单。 菜单的 Callback 属性 Graphice User Interface(GUI) 68

Application Programming Interface Interface with C,fortran,excel

Application Programming Interface Example for C

complier 1.mcc mcc[-options] fun [fun2...] [mexfile1...] mlibfile1...] 2.Tools

complier 2.Tools Deployment project Code Generation Project

complier 2.Tools Deployment project Code Generation Project

一旦你学会了基本语法,设计程序的能力 取决于你的知识和掌握函数的多少及熟练 程度. Once you learn the basic syntax, the ability of the program design depends on your knowledge and how many functions you have mastered and proficiency. Practice and practice

Thanks!