CSE123 Lecture 3 Files and File ManagementScripts.

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

Introduction to Matlab
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Programming with MATLAB
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to MATLAB
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB.
CSE123 Introduction to Computing
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014
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.
January 24, 2005 Lecture 3 - By P. Lin 1 CPET 190 Lecture 3 Problem Solving with MATLAB
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
MATLAB File Management. MATLAB User File Management Matlab provides a group of commands to manage user files. For more information, type help iofun. pwd.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
CSE123 Lecture 3 Different types of Variables Logical operators, Conditional Statements and If Blocks.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Script M-Files Group of Matlab commands placed in a text file with a text editor. Matlab can open and execute the commands exactly as if they were entered.
Digital Image Processing Lecture4: Fundamentals. Digital Image Representation An image can be defined as a two- dimensional function, f(x,y), where x.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB Lecture 18.
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Introduction to Matlab By E. Noura Semary. Contents MATLAB Environment  Command window, Workspace, Path window, Editor window,and Figure window) Basic.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Review if imag(x) > 0 fprintf('Sorry, but I don''t understand complex numbers.\n'); return end if x < 10 % leave this out, type the next line first, and.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
Matlab Programming a logical approach. Outline Announcements: –Homework I: due Wed. by 5, by –Last day to add/drop or change credit/audit Iteration.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
1 Lecture 4 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
INTRODUCTION TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators.
EEE 161 Applied Electromagnetics
Chapter 4 MATLAB Programming
Other Kinds of Arrays Chapter 11
MATLAB DENC 2533 ECADD LAB 9.
Arithmetic operations, decisions and looping
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Logical Operations In Matlab.
Note on Indexing of Array Elements
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Matlab Basics.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

CSE123 Lecture 3 Files and File ManagementScripts

Matlab provides a group of commands to manage user files pwd: Print working directory – displays the full path of the present working directory. cd path: Change to directory (folder) given by path, which can be either a relative or absolute path. dir : Display the names of the directories (folders) and files in the present working directory. what: Display the names of the M-files and MAT-files in the current directory. delete file: Delete file from current directory type file: Display contents of file (text file only, such as an M-file).

Saving and Restoring Matlab Information It is good engineering practice to keep records of calculations. These records can be used for several purposes, including: To revise the calculations at a later time. To prepare a report on the project. Diary Command The diary commands allows you to record all of the input and displayed output from a Matlab interactive workspace session. The commands include: diary file: Saves all text from the Matlab session, except for the prompts (>>), as text in file, written to the present working directory. If file is not specified, the information is written to the file named diary. diary off: Suspends diary operation. diary on: Turns diary operation back on. diary: Toggles diary state

Saving and Restoring Matlab Information Example: >> diary roots >> a=1; >> b=5; >> c=6; >> x = -b/(2*a); >> y = sqrt(b^2-4*a*c)/(2*a); >> s1 = x+y s1 = -2 >> s2 = x-y s2 = -3 The file roots is written in your current working directory. It can be displayed by Matlab command type roots.

Storing and Loading Workspace Values save : Stores workspace values (variable names, sizes, and values), in the binary file matlab.mat in the present working directory save data : Stores all workspace values in the file data.mat save data_1 x y :Stores only the variables x and y in the file data_1.mat load data_1 :Loads the values of the workspace values previously stored in the file data_1.mat

Script M-Files Group of Matlab commands placed in a text file with a text editor. Matlab can open and execute the commands exactly as if they were entered at the Matlab prompt. The term “script” indicates that Matlab reads from the “script” found in the file. Also called “M-files,” as the filenames must end with the extension ‘.m’, e.g. example1.m.

Script M-Files Example : Create the file named qroots.m in your present working directory using a text editor: %qroots:Quadratic root finding script format compact; a=1; b=5; c=6; x = -b/(2*a); y=sqrt(b^2-4*a*c)/(2*a); s1 = x+y s2 = x-y To execute the script M-file, simply type the name of the script file qroots at the Matlab prompt: >> qroots a = 1 b = 5 c = 43 6 s1 = -2 s2 = -3

Effective Use of Script Files 1. The name must begin with a letter and may include digits and the underscore character. 2. Do not give a script file the same name as a variable it computes 3. Do not give a script file the same name as a Matlab command or function. To check existence of command, type exist(’rqroot’). This command returns one of the following values: 0 if rqroot does not exist 1 if rqroot is a variable in the workspace 2 if rqroot is an M-file or a file of unknown type in the Matlab search path ….

Effective Use of Script Files 4. All variables created by a script file are defined as variables in the workspace. After script execution, you can type who or whos to display information about the names, data types and sizes of these variables. 5. You can use the type command to display an M-file without opening it with a text editor. For example, to view the file rqroot.m, the command is type rqroot.

Matlab Search Path, Path Management Matlab search path: Ordered list of directories that Matlab searches to find script and function M-files stored on disk. Commands to manage this search path: matlabpath: Display search path. addpath dir: Add directory dir to beginning of matlabpath. If you create a directory to store your script and function M-files, you will want to add this directory to the search path. rmpath dir: Remove directory dir from the matlabpath.

Different types of Variables Logical operators, Conditional Statements and If Blocks

 Complex. a + b i a and b are real numbers i is an imaginary number. ( i 2 = -1 ) Different types of Variables  Integer. positive whole numbers {1, 2, 3,... } negative whole numbers {-1, -2, -3,... } zero {0} Matlab Notation N= a+bi or N=a+bj Matlab Notation N= a+bi or N=a+bj  Real. real number. Matrix index (ex: B(2,1) ) Counters All calculus results… Complex calculus Geometry Vector calculus A= 5+10i; B= j; Examples: Numerical Variables

 Character/string. Strings of alphanumeric elements Different types of Variables Matlab Notation A=’string’ Matlab Notation A=’string’ All labels and titles. Filenames Strings and characters follow the same rules as other matrices, with each character counting for one element. >>myname=’James’; >>whos myname Name Size Bytes Class myname 1x5 10 char array Example: name=’ James’; Date=’October 7th’; Examples: Character/string Variables

Logical Variables  Logical Variables or Boolean. Logical expression with 2 states: 0 or 1 which means: false or true Condition statements Decision making >>A=true A = 1 >> whos A Name Size Bytes Class A 1x1 1 logical array Example: >>B=false B = 0 >> whos B Name Size Bytes Class B 1x1 1 logical array Example: Different types of Variables

Structured Programming Initialization Calculation Results Input Initialization Sequential Programming Structured Programming Input Calculation Calculation 1Calculation 2 Initialization Result 1Result 2 ? Decision making Condition statements

Relational Operators  Decision making uses comparison of logical variables  Comparison is done by creating logical expressions Format of SIMPLE Logical Expressions: ****** expression1 relational-operator expression2****** relational- operator Comparison ==Is equal to >Is greater than <Is smaller than >=Is greater or equal to <=Is smaller or equal to ~=Is not equal to >> A=1; B=2; >> A==B Example: ans = 0 >> A>B ans = 0 >> A<B ans = 1 >> A>=B ans = 0 >> A<=B ans = 1 >> A~=B ans = 1

Logical Operators Format of COMPOUND Logical Expressions: (exp1 relational-op exp2) Logical operator (exp3 relational-op exp4) Logical operator operation &and |or xoror (exclusive) ~not ABC= A&B ABC= A|B AB C= xor(A,B) Truth Table ~(A&B) ~xor(A,B) ~(A|B)

Logical Variables >> A=1; B=2; >> (A==B) & (A>B) Examples: >> (A<B) & (A==B) ans = 0 >> (A==B) | (A>B)ans = 0 >> (A<B) | (A==B) ans = 1 >> xor( (A==B), (A<B) ) ans = 1 >> ~(A<B) ans = 0 >> xor( (A~=B), (A<B) ) >> ~(A>B) ans = 1 ans = 0 >> (A>0) & (B>A)ans = 1 >> (A>0) & (B>A)&(B<0) ans = 0

Structured Programming Format of if statement: if Logical Expression Statements …… end if True False Statement Format of if else statement: if Logical Expression Statement 1 else Statement 2 end if True False Statement1Statement2

Example: iftest1.m % Program to test the if statement #1 X=input(‘Enter value for x:’); if X>=0 Y=sqrt(X); fprintf(‘The squareroot of %3.2f is %4.3f’,X,Y) end % Program to test the if statement #1 X=input(‘Enter value for x:’); if X>=0 Y=sqrt(X); fprintf(‘The squareroot of %3.2f is %4.3f’,X,Y) end >>iftest1 Enter value for x: 9 The squareroot of 9.00 is >>iftest1 Enter value for x: 9 The squareroot of 9.00 is Input X Calculate If X>=0 Initialization Display Result End of script True False >>iftest1 Enter value for x: -2 >> Structured Programming

Example: iftest2.m % Program to test the if statement #2 X=input(‘Enter value for x:’); if X>=0 Y=sqrt(X); fprintf(‘The squareroot of %3.2f is %3.4f’,X,Y) else disp(‘x is negative: there is no real result’) end % Program to test the if statement #2 X=input(‘Enter value for x:’); if X>=0 Y=sqrt(X); fprintf(‘The squareroot of %3.2f is %3.4f’,X,Y) else disp(‘x is negative: there is no real result’) end >>iftest2 Enter value for x: 3 The squareroot of 9.00 is >>iftest2 Enter value for x: -2 x is negative: there is no real result >> >>iftest2 Enter value for x: 3 The squareroot of 9.00 is >>iftest2 Enter value for x: -2 x is negative: there is no real result >> Input X Calculate If X>=0 Initialization Display Result End of script True False Display NO Result Structured Programming

Format of if elseif else statement: if Logical Expression Statements 1 elseif Logical Expression Statements 2 else Statements 3 end if False Statement1 elseif Statement2 Statement3 True False True Structured Programming

Example: iftest3.m % Program to test the if statement #3 X=input(‘Enter value for x:’); if X>0 disp(‘x is positive’); elseif X<0 disp(‘x is negative’); else disp(‘x equal 0’); end % Program to test the if statement #3 X=input(‘Enter value for x:’); if X>0 disp(‘x is positive’); elseif X<0 disp(‘x is negative’); else disp(‘x equal 0’); end >>iftest3 Enter value for x: 3 x is positive >>iftest3 Enter value for x: -2 x is negative >>iftest3 Enter value for x: 3 x is positive >>iftest3 Enter value for x: -2 x is negative Input X If X>0 Initialization End of script True False Display Result >0 Display Result <0 If X<0 Display Result = 0 True False Structured Programming

Problem: Pick a random number N (-2<N<2) Calculate B= “nesting “ If N positive calculate: A=log(N) if A positive calculate: B=sqrt(A) % nested “if statements” example N= rand(1)*4-2; if N>=0 A=log(N); if A>0 B=sqrt(A); end % nested “if statements” example N= rand(1)*4-2; if N>=0 A=log(N); if A>0 B=sqrt(A); end % nested “if statements” example N= rand(1)*4-2; if N>=0 A=log(N); if A>0 B=sqrt(A); end % nested “if statements” example N= rand(1)*4-2; if N>=0 A=log(N); if A>0 B=sqrt(A); end Use indentation (Tab key) Structured Programming

The “ SWITCH” structure switch variable case test1 Statement 1 case test2 Statement 2 ….. otherwise Statement n end Statement3 Switch Statement nStatement1 Statement4Statement2 Structured Programming

The “ SWITCH” structure % program to test switch A=input('Your choice [1,2 3] ? '); switch A case 1 disp('Choice 1') case 2 disp('Choice 2') case 3 disp('Choice 3') otherwise disp('Wrong choice') end % program to test switch A=input('Your choice [1,2 3] ? '); switch A case 1 disp('Choice 1') case 2 disp('Choice 2') case 3 disp('Choice 3') otherwise disp('Wrong choice') end >> Testswitch Your choice [1,2 3] ? 1 Choice 1 >> Testswitch Your choice [1,2 3] ? 7 Wrong choice >> Testswitch Your choice [1,2 3] ? 2 Choice 2 >> Testswitch Your choice [1,2 3] ? 3 Choice 3

Example1 Write a script example.m to find roots of a second order equation ax 2 +bx+c=0. When the script is executed it will –ask the user enter the coefficients a,b,c –calculate discriminant –calculate the roots and display the case according to sign of discriminant.

Example2 Write a script that allows a user to enter a string containing a day of a week (“Sunday”, “Monday” etc) uses a switch construct to convert the day to its corresponding number, where Monday is the first day of the week. Print out the resulting day number. Also be sure to handle the case of an illegal day name.