28
CSE123 Lecture 3 CSE123 Lecture 3 Files and File Management Scripts Scripts

CSE123 Lecture 3 Files and File ManagementScripts

Embed Size (px)

Citation preview

Page 1: CSE123 Lecture 3 Files and File ManagementScripts

CSE123 Lecture 3CSE123 Lecture 3

Files and File Management

ScriptsScripts

Page 2: CSE123 Lecture 3 Files and File ManagementScripts

Files and File ManagementMatlab 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).

Page 3: CSE123 Lecture 3 Files and File ManagementScripts

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 CommandThe 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

Page 4: CSE123 Lecture 3 Files and File ManagementScripts

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+ys1 =-2>> s2 = x-ys2 =-3

The file roots is written in your current working directory. It can be displayed by Matlab command type roots.

Page 5: CSE123 Lecture 3 Files and File ManagementScripts

Storing and Loading Workspace Values

save : Stores workspace values (variable names, sizes, and values), in the binary file matlab.mat in the present working directorysave data :Stores all workspace values in the file data.matsave data_1 x y :Stores only the variables x and y in the file data_1.matload data_1 :Loads the values of the workspace values previously stored in the file data_1.mat

Page 6: CSE123 Lecture 3 Files and File ManagementScripts

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.

Page 7: CSE123 Lecture 3 Files and File ManagementScripts

Script M-FilesExample : 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+ys2 = x-y

To execute the script M-file, simply type the name of the script file qroots at the Matlab prompt:>> qrootsa =1b =5c =436s1 =-2s2 =-3

Page 8: CSE123 Lecture 3 Files and File ManagementScripts

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 computes3. 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 exist1 if rqroot is a variable in the workspace2 if rqroot is an M-file or a file of unknown type in

the Matlab search path….

Page 9: CSE123 Lecture 3 Files and File ManagementScripts

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.

Page 10: CSE123 Lecture 3 Files and File ManagementScripts

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.

Page 11: CSE123 Lecture 3 Files and File ManagementScripts

Different types of Variables Different types of Variables Logical operatorsLogical operators, , Conditional StatementsConditional Statements

and If Blocksand If Blocks

Page 12: CSE123 Lecture 3 Files and File ManagementScripts

Complex. a + b i

• a and b are real numbers

• i is an imaginary number. ( i2= -1 )

Different types of VariablesDifferent types of Variables

Integer.

positive whole numbers {1, 2, 3,... }

negative whole numbers {-1, -2, -3,... }

zero {0}

Matlab NotationN= a+bi

orN=a+bj

Matlab NotationN= a+bi

orN=a+bj

Real. real number.

Matrix index (ex: B(2,1) )

Counters

All calculus results…

Complex calculus

Geometry Vector calculus

A= 5+10i;B=2.5+20.2j;

Examples:

Numerical Variables

Page 13: CSE123 Lecture 3 Files and File ManagementScripts

Character/string.

Strings of alphanumeric elements

Different types of VariablesDifferent types of Variables

Matlab NotationA=’string’

Matlab NotationA=’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

Page 14: CSE123 Lecture 3 Files and File ManagementScripts

Logical Variables

Logical Variables or Boolean.Logical expression with 2 states:

0 or 1

which means: false or true

Condition statements

Decision making

>>A=trueA = 1>> whos A Name Size Bytes Class

A 1x1 1 logical array

Example:

>>B=falseB = 0>> whos B Name Size Bytes Class

B 1x1 1 logical array

Example:

Different types of VariablesDifferent types of Variables

Page 15: CSE123 Lecture 3 Files and File ManagementScripts

Structured Programming

Initialization

Calculation

Results

Input

Initialization

Sequential Programming Structured Programming

Input

Calculation

Calculation 1 Calculation 2

Initialization

Result 1 Result 2

?Decision making

Condition statements

Page 16: CSE123 Lecture 3 Files and File ManagementScripts

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

Page 17: CSE123 Lecture 3 Files and File ManagementScripts

Logical Operators

Format of COMPOUND Logical Expressions:

 (exp1 relational-op exp2) Logical operator (exp3 relational-op

exp4) Logical operator

operation

& and

| or

xor or (exclusive)

~ not

A B C= A&B

0 0 0

0 1 0

1 0 0

1 1 1

A B C= A|B

0 0 0

0 1 1

1 0 1

1 1 1

A B C= xor(A,B)

0 0 0

0 1 1

1 0 1

1 1 0

TruthTable

~(A&B)

1

1

1

0

~xor(A,B)

1

0

0

1

~(A|B)

1

0

0

0

Page 18: CSE123 Lecture 3 Files and File ManagementScripts

Logical Variables

>> A=1; B=2;

>> (A==B) & (A>B)

Examples:

>> (A<B) & (A==B) ans = 0ans = 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

Page 19: CSE123 Lecture 3 Files and File ManagementScripts

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

Statement1 Statement2

Page 20: CSE123 Lecture 3 Files and File ManagementScripts

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

>>iftest1Enter value for x: 9The squareroot of 9.00 is 3.0000

>>iftest1Enter value for x: 9The squareroot of 9.00 is 3.0000

Input X

Calculate

If X>=0

Initialization

Display Result

X

End of script

True

False

>>iftest1Enter value for x: -2

>>

Structured Programming

Page 21: CSE123 Lecture 3 Files and File ManagementScripts

Example: iftest2.m % Program to test the if statement #2X=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 #2X=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

>>iftest2Enter value for x: 3The squareroot of 9.00 is 3.0000>>iftest2Enter value for x: -2x is negative: there is no real result>>

>>iftest2Enter value for x: 3The squareroot of 9.00 is 3.0000>>iftest2Enter value for x: -2x is negative: there is no real result>>

Input X

Calculate

If X>=0

Initialization

Display Result

X

End of script

True

False

Display NO Result

Structured Programming

Page 22: CSE123 Lecture 3 Files and File ManagementScripts

Format of if elseif else statement:  if Logical Expression Statements 1 elseif Logical Expression Statements 2 else

Statements 3 end

ifFalse

Statement1

elseif

Statement2 Statement3

True

False

True

Structured Programming

Page 23: CSE123 Lecture 3 Files and File ManagementScripts

Example: iftest3.m % Program to test the if statement #3X=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 #3X=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

>>iftest3Enter value for x: 3x is positive>>iftest3Enter value for x: -2x is negative

>>iftest3Enter value for x: 3x is positive>>iftest3Enter value for x: -2x 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

Page 24: CSE123 Lecture 3 Files and File ManagementScripts

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)

log( )N

% nested “if statements” example

N= rand(1)*4-2;

if N>=0A=log(N);if A>0B=sqrt(A);endend

% nested “if statements” example

N= rand(1)*4-2;

if N>=0A=log(N);if A>0B=sqrt(A);endend

% nested “if statements” example

N= rand(1)*4-2;

if N>=0 A=log(N); if A>0 B=sqrt(A); endend

% nested “if statements” example

N= rand(1)*4-2;

if N>=0 A=log(N); if A>0 B=sqrt(A); endend

Useindentation(Tab key)

Structured Programming

Page 25: CSE123 Lecture 3 Files and File ManagementScripts

The “SWITCH” structure

 switch variable

case test1 Statement 1case test2 Statement 2 …..otherwise Statement nend

Statement3

Switch

Statement nStatement1

Statement4Statement2

Structured Programming

Page 26: CSE123 Lecture 3 Files and File ManagementScripts

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

Page 27: CSE123 Lecture 3 Files and File ManagementScripts

Example1

Write a script example.m to find roots of a second order equation

ax2+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.

Page 28: CSE123 Lecture 3 Files and File ManagementScripts

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.