Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using Script Files and Managing Data

Similar presentations


Presentation on theme: "Using Script Files and Managing Data"— Presentation transcript:

1 Using Script Files and Managing Data

2 In this chapter will study
How to input data into a script file How MATLAB stores data Ways to display and save data How to exchange data between MATLAB and other programs

3 How to program in MATLAB
1. To create a new program, use the Script option under the New menu or enter the edit command in the command window (like edit prog1 – prog1 being the name of your program). You now have a blank editor window (script editor). 2. Enter your code and save your script using the Save button. 3. Run your script by pressing the Run button or enter the script's name in the command window: >>prog1. Now let's start with the basics of data management and MATLAB programming.

4 Basic MATLAB Programming
We know already that variables are containers of data. We also know that we can use commands to ask MATLAB to do certain operations. We know as well that a programming mode exists in MATLAB, permitting us to send multiple instructions being executed one after the other. We can save this program as an .m file.

5 Can assign a value to a variable in three ways
INPUT TO A SCRIPT FILE When MATLAB executes (runs) a script file, any variables used in file must already have values assigned to them, i.e., the variables must already be in the workspace Can assign a value to a variable in three ways

6 1. Assign value in script file
INPUT TO A SCRIPT FILE 1. Assign value in script file Assignment statement is part of script To use different value, must edit file, save file, and run file again Note – when variable value (a number) is part of script, value is said to be hard-coded

7 Using Variables in Simple Scripts
Method 1: You assign the values in the program itself (we saw that before remember? the = operator).

8 2. Assign value in Command Window
INPUT TO A SCRIPT FILE 2. Assign value in Command Window Define variable and assign its value in Command Window From before, know that script file will recognize variable To use different value, assign new value in Command Window and run file again Don't need to resave file Instead of retyping entire command, use up-arrow to recall command and then edit it T I P

9 Using variables in simple scripts
Method 2: Defining the variables in the command window before running the script. => Advantage: More versatile as the script can produce a different result at every run depending on the variable values. Try it! Instead of retyping entire command, use up-arrow to recall command and then edit it. Remember? T I P

10 Here is an example:

11 INPUT TO A SCRIPT FILE

12 3. Assign by prompt in script file
INPUT TO A SCRIPT FILE 3. Assign by prompt in script file Script file prompts (asks) user to enter a value, then script assigns that value to a variable Use MATLAB input command to ask for and get value from user

13 Using variables in simple scripts
Method 3: Assign by prompt in script file (meaning ask the user to fill the variables values). The program prompts (asks) user to enter a value, then the script assigns that value to a variable. Use the MATLAB input command to ask for and get a value from the user variable_name = input('prompt') prompt is the text that the input command will display in the Command Window (must be between single quotes).

14 Input Command – How It Works
variable_name = input('prompt') When the script executes the input command: It displays the prompt text in the Command Window. It puts the cursor immediately to the right of prompt. The user types the value and presses ENTER. The script assigns the user's entered value to variable and displays the value unless the input command has a semicolon at the end.

15 Input Command – Example
R E S U L T

16 Input Command – User Fills Variable
It is good form to put a space, or a colon and a space, at the end of the prompt so that the user's entry is separated from the prompt. For example (if the user enters 1994): age = input('Year of birth'); Year of birth age = input('Year of birth '); Year of birth 1994 age = input('Year of birth: '); Year of birth: 1994 T I P Bad! Better! Best!

17 Input Command – User Fills Variable
But what if you want to fill the variable with a string like a name or a sentence? city = input ('City of birth: ') If you enter just Toronto, you will get an error. You must enter the quotes to indicate that it is a string: 'Toronto'. City of birth: 'Toronto' But there is another way. You can use the 's' qualifier: city = input ('City of birth: ', 's') City of birth: Toronto

18 Output Commands: disp and fprintf
We know that when omit the semicolon at end of a statement, MATLAB displays the result on screen. You have no control over the appearance of the result (how many lines, what precision in numbers...) You can use the MATLAB command disp for some control of appearance and fprintf for full control.

19 The disp Command disp (display): Displays variable values or text on the screen. Each display appears on a separate line. It doesn't show the variable name, only its value. disp only offers limited control of display. For the best control of display we can use fprintf. disp(variable_name) or disp('text string')

20 The fprintf Command fprintf means file print formatted.
You can write to the screen or to a file. You can mix numbers and text in the output. You have the full control of the output display but it is a little bit more complicated to use than disp.

21 The fprintf Command – A simple sentence
>> fprintf ('The quick brown fox') The quick brown fox>> Problem – The Command Window displays the command prompt (>>) at end of the text, not at start of next line! Not pretty! The solution is to use a \n (new line) character at the end of the sentence. Looks much better! >> fprintf ('The quick brown fox\n') The quick brown fox >>

22 You can use as many \n in your fprintf as you like.
The \n Character You can use as many \n in your fprintf as you like. >> fprintf('Get\nBusy\nNow!\n\n') Get Busy Now! >> One extra blank line

23 Integer Placeholders %d is the default integer placeholder. When used it will simply display the value as is without any padding. To add padding, to have nicely aligned columns for example, we need formatted placeholders. %nd will reserve n places to display the number. Justification will be to the right. The negative sign takes one place. If the value is 17 and %4d is used, then it will display 2 blank spaces followed by 17 on the screen: ##17 We use # to represent a blank space here but blank spaces are really invisible.

24 fprintf Command – Printing a Variable
What if I want to print out the value of a variable? We can do that using a more advanced form of fprintf containing two parts: a string (including placeholders), and the arguments (the variable themselves). Here is a simple example with one numeric variable following a sentence. >>year = 1867; >>fprintf ('The year is %d\n', year) The year is >> You can also print without any extra text (aka labeling): >>fprintf ('%d\n', year) >> This is a placeholder

25 fprintf: Printing More Than One Variable
You can print more than one variable in the same fprintf, like this following example: >> day = 25; temperature = 20; >> fprintf ('It is October %d, and the temperature is %d degrees.\n', day, temperature) It is October 25 and the temperature is 20 degrees. >> The number of variables and placeholders must be the same. The first placeholder formats the first variable, the second placeholder formats the second variable, and so on...

26 Integer Placeholders Rules
The number is always displayed in its entirety, even when the format is too narrow. With and a %3d placeholder, you would see -1234, therefore using 5 spaces instead of the 3 requested. A negative number in the placeholder changes the justification to the left of the field. For example, with a value of –1234 and a %–8d placeholder, the display will be –1234###. Three trailing blank spaces

27 Floating Point Placeholders
By default the %f placeholder displays the number with 6 decimal digits and no padding (may vary depending on computer system). The formatted double placeholder has this format: %w.df, where w is the total width of the field (including sign and decimal point) and d the number of decimal digits. If the value is 4.56 and the placeholder is %6.3f, then the display will be #4.560 One leading blank space

28 Floating Point Placeholders Rules
With a floating point formatted print, you always get the requested number of digits to the right of the decimal point (even if the field is not wide enough). You also always (like the integer placeholder) get all the significant numbers (the numbers to the left of the decimal point). However, if there are more decimal precision in the value than are requested in the placeholder, the value is truncated to match the placeholder size and rounded up if need be.

29 Floating Point Placeholder Examples
If the value is and the placeholder is %7.3f, then you will get 3 decimal digits as requested plus the significant numbers: for a total of 7 spaces. If the value is and the placeholder is %8.3f, then you will get 3 decimal digits as requested plus the significant numbers and padding: ## Note the rounding-up effect. If the value is and the placeholder is %8.7f it will display Note: Internal values in the computer's memory are unaffected by placeholders (just look at the workspace). Two leading blank spaces

30 The %e placeholder – Scientific Notation
%e works like %f Here are a few examples with printing the value of pi: >> fprintf( 'pi is about %f\n', pi ) pi is about >> fprintf( 'pi is about %10.8f\n', pi ) pi is about >> fprintf( 'pi is about %10.8e\n', pi ) pi is about e+00 >> fprintf( 'pi is about %10.2e\n', pi ) pi is about 3.14e+00 Two leading blank spaces here

31 Escape Characters in fprintf
What if you want to use reserved characters in an fprintf? Use escape characters to display characters used in placeholders. To display a percent sign, use %% in the text. fprintf('100%%\n') % To display a single quote, use ' ' in the text (two sequential single quotes). fprintf('Martha''s Vineyard') Martha's Vineyard To display a backslash, use \\ in the text (two sequential backslashes). fprintf('Nantucket\\ACK') Nantucket\ACK

32 Long fprintf Command Format strings are often long. You can break a string by: Put an open square bracket ( [ ) in front of the first single quote. Put a second single quote where you want to stop the line. Follow that quote with an ellipsis (three dots). Press ENTER, which moves cursor to next line. Type in the remaining text in single quotes. Put a close square bracket ( ] ). Put the rest of the fprintf command. See example on the next slide.

33 Long fprintf Command - Example
>> weight = 178.3; >> age = 17; >> fprintf( ['Tim weighing %.1f lbs'... ' is %d years old'], weight, age ) Tim weighing lbs is 17 years old

34 fid = fopen('file_name','permission')
fprintf and Files: Step 1 You can also use the fprintf command to save the output to a file instead of displaying in the command window. It takes three steps to write to a file: Step 1: Open the file fid = fopen('file_name','permission') fid: file identifier, to let fprintf know what file to write its output in. permission: tells how file will be used: for reading, writing, or appending. Ex: >> fid = fopen('output.txt', 'w');

35 fprintf and Files : Permissions
Some common permission codes: r : open file for reading only. w : open file for writing. If the file already exists, the content is deleted. If the file doesn't exist, a new file is created. a : same as w except that if the file already exists the written data is appended to the end of the file. If no permission code specified, fopen uses r. See Help on fopen for more advanced codes

36 fprintf and Files: Step 2 Step 2:
Write to the file with fprintf. Use it exactly as before but insert fid before the format string: fprintf(fid,'format string',variables) The passed fid is how fprintf knows to write to the file instead of display on the screen Ex: >> fprintf (fid, 'Age = %d\n', age);

37 fprintf and Files: Step 3
When you're done writing to the file, close it with >> fclose(fid); Once you close it, you can't use that fid anymore until you get a new one by calling fopen. It is good form to close your files when you no longer need them. Especially important for files open in writing ('w' or 'a').

38 Notes on Data Files If the file name you give to fopen has no path, MATLAB writes it to the current directory, also called the working directory. You can have multiple files open simultaneously and use fprintf to write to all of them just by using different fids. Files are written in raw text. You can read the files you make with fprintf in any text editor like MATLAB's Editor/Debugger window or Notepad.

39 Reading from files: fscanf
To read data from a text file, we use the fscanf command (need to do fopen first of course). Example script: a = 20; b = 30; c = 40; out = fopen ('data.txt', 'w'); fprintf (out, '%d %d %d', a, b, c); fclose (out); in = fopen ('data.txt', 'r'); v = fscanf (in, '%d') fclose(in); File created and filled OUTPUT v = 20 30 40

40 Exporting Data: Sharing With Other Programs
Remember that we used save and load to keep our MATLAB variables (workspace) from one session to the other? We can use a special save to export our variables to programs other than MATLAB: To save as formatted text (also called ASCII text). For example, >> save filename.txt –ascii; Note: Saves only the values, not their names!

41 Importing from Spreadsheet – Part 1
Let’s have a spreadsheet with data created with Excel or OpenOffice or LibreOffice. Now export or save as your spreadsheet as an XLS file or a CSV text. Use the comma as your delimiter for CSV. The CSV file will look like this:

42 Importing from Spreadsheet – Part 2
There are two ways to import data files. The easiest way is to use the import wizard. You can import easily the XLS or CSV files. Use the Import Data button to start the wizard. Locate the file you wish to import. You might have to expand the This PC entry for Windows. Note: I you use vapps, you need to use the full version of the Citrix receiver to import from external disks. It will not work with the Lite version. Next select the kind of structure you wish to put your imported date into (column vectors, numeric matrix,… and click the green check mark to import.

43 Importing from Spreadsheet – Part 3
IMPORT INTO CLICK HERE

44 Importing from Spreadsheet – Part 4
Close the import window and note that the workspace contains the imported variables. In this example data was imported as column vectors.

45 Importing from Spreadsheet – Part 5
You can also import data by using commands in a script.. Use csvread for CSV files and xlsread for XLS files. If you use vapps, it is highly recommended to copy the data files onto your Personal VApps Storage (V:) drive, ideally in the same folder you saved your script (.m) file in. Go to goo.gl/ogE7ZC to learn more about the Personal VApps Storage.

46 Importing from Spreadsheet – Part 6
You can import data from an XLS file with: variable_name = xlsread('filename.xls') You can import data from a CSV file with: variable_name = csvread('filename.csv') You can also export from MATLAB to XLS with: xlswrite('filename.xls', variable_name) You can also export from MATLAB to CSV with: xlswrite('filename.csv', variable_name

47 End of lesson

48 Extra Readings! MUST READ!

49 IMPORTING AND EXPORTING DATA
MATLAB often used to analyze data collected by other programs Sometimes need to transfer MATLAB data to other programs In this section will only discuss numerical data MATLAB has commands to load and save data from a number of other programs Can also tell MATLAB what format data is in

50 IMPORTING AND EXPORTING DATA
Will illustrate transferring data with a specific program by discussing Microsoft Excel Commonly used to store data Works with many programs that gathers data Used often by people with technical data but for which MATLAB is overkill

51 IMPORTING AND EXPORTING DATA
Importing and exporting data into and from Excel: Import (read) data from Excel with variable_name=xlsread('filename') Stores all data in one variable If Excel file has multiple sheets, reads first one To read from other sheets, pass command the sheet name Can read rectangular section of sheet by specifying range in command

52 Export (write) data to Excel file with
IMPORTING AND EXPORTING DATA Export (write) data to Excel file with xlswrite('filename',variable_name) Can specify in command name of sheet and range to write to

53 IMPORTING AND EXPORTING DATA
MATLAB's import wizard is semi-automatic way to read data from any file Wizard shows what it thinks format is User can then adjust format Two ways to start Import Wizard In Command Window, File|Import Data With command uiimport

54

55 IMPORTING AND EXPORTING DATA
First Wizard display Wizard displays file-selection dialog box, user picks file Wizard shows some of data as it is in file and as how Wizard interprets it User can change column separator or number of text header lines (that Wizard will not try to read)

56 IMPORTING AND EXPORTING DATA
Second Wizard display Shows name and size of variable it will create When user selects Finish, Wizard creates that variable in workspace Variable name is file name

57 THE save AND load COMMANDS
Use save command to save some or all workspace variables to hard drive Two forms save file_name save('file_name') Either one saves all workspace variables, including their name, type, size, value

58 save file_name var1 var2 save('file_name','var1','var2')
THE save COMMAND To only save specific variables, list variables after file name. For example, to save two variables named var1 and var2 save file_name var1 var2 save('file_name','var1','var2')

59 All forms store variables in file called "file_name.mat"
THE save COMMAND All forms store variables in file called "file_name.mat" Called "mat" file Unformatted (binary) file Only MATLAB can read mat file, not other programs Can't read file in text editor, or MATLAB Editor/Debugger Window

60 THE load COMMAND To load data in a mat file into workspace
load file_name load( 'file_name') To load only specific variables from mat file, e.g., var1 and var2 load file_name var1 var2 load('file_name','var1','var2') If variable already exists in workspace, it is overwritten (its value is replaced by value in file)

61 THE load COMMAND To load data in a text file into workspace
load file_name variable = load( 'file_name') In first form, creates variable called file_name and stores all file data in it If all rows in file don't have same number of columns, MATLAB displays an error Even if data created from multiple variables all with same number of columns, load still reads all data into one variable Not very useful in this case

62 INPUT TO A SCRIPT FILE It's helpful to put a space, or a colon and a space, at the end of the prompt so that the user's entry is separated from the prompt. Example script file: age = input('Age in 2012'); age = input('Age in 2012 '); age = input('Age in 2012: '); T I P

63 Output of script shown with value of "30" that user entered
INPUT TO A SCRIPT FILE Output of script shown with value of "30" that user entered Age in Age in Age in 2012: 30 T I P bad better good

64 >> name = input( 'Your name: ' ) Your name: 'Joe' name = Joe
INPUT TO A SCRIPT FILE Can also prompt for and assign a text string to a variable. Method 1 Use input as before but user must type in beginning and ending quote marks >> name = input( 'Your name: ' ) Your name: 'Joe' name = Joe User must type quotes

65 variable_name=input('prompt', 's')
INPUT TO A SCRIPT FILE Method 2 Pass 's' as second argument to input. User should not enter quotes variable_name=input('prompt', 's') >> name=input('Your name: ', 's') Your name: Joe name = Joe User enters without quotes

66 MATLAB Display Formats

67 Can display tables with headers using disp
The disp Command Can display tables with headers using disp Clumsy because no control of column width – must adjust headers by inserting blanks Better to use fprintf

68 The fprintf Command Means file print formatted
formatted text is text that can be read by people unformatted text looks random to people but computers can read it Can write to screen or to a file Can mix numbers and text in output Have full control of output display More complicated to use

69 fprintf('Text to display')
The fprintf Command Using the fprintf command to display text: Display text with fprintf('Text to display') Example >> fprintf( 'Howdy neighbor' ) Howdy neighbor>> Problem – Command Window displays prompt (>>) at end of text, not at start of next line! Not looking good

70 characters "\n" at the end of the fprintf text
The fprintf Command To make the next thing that MATLAB writes (after a use of fprintf) appear on the start of a new line, put the two characters "\n" at the end of the fprintf text >> fprintf( 'Howdy neighbor\n' ) Howdy neighbor >> T I P

71 The fprintf Command Can also use \n in middle of text to make MATLAB display remainder of text on next line >> fprintf('A man\nA plan\nPanama\n') A man A plan Panama >>

72 \n – makes following text come out at start of next line
The fprintf Command \n is an escape character, a special combination of two characters that makes fprintf do something instead of print the two characters \n – makes following text come out at start of next line \t – horizontal tab There are a few more

73 fprintf Command – Printing a variable
What if I want to print out the value of a variable? We can do that using a more advanced form of fprintf containing two parts: a string (including placeholders), and the arguments (the variable themselves). Here is a simple example with one numeric variable following a sentence. >>year = 2014; >>fprintf ('The year is %d\n', year) The year is >> You can also print without labeling: >>fprintf ('%d\n', year) >> placeholder

74 fprintf: Printing more than one variable
You can print more than one variable in an fprintf. >> age = 25; weight = 75; >> fprintf ('Joe is %d, weighs %d kilos\n', age, weight) Joe is 25, weighs 75 kilos >> The number of variables and placeholders must be the same. The leftmost placeholder formats the leftmost variable, the second from left formats the second from left variable, etc...

75 Integer Placeholders %d is the default integer placeholder. When used it will simply display the value as is without any padding. To add padding, to have columns for example, we need formatted placeholders. %nd will reserve n places to display the number. Justification will be to the right. The negative sign takes one place. If the value is 17 and %4d is used, then it will display 2 spaces followed by 17 on the screen: _ _17 Two leading blanks

76 Integer Placeholders The number is always displayed in its entirety, even when the format is too narrow. With and a %3d placeholder, you would see -1234, therefore using 5 spaces instead of the 3 requested. A negative number in the placeholder changes the justification to the left of the field. For example, with a value of –1234 and a %–8d placeholder, the display will be –1234_ _ _ . Three trailing blanks

77 Floating Point Placeholders
By default the %f placeholder displays the number with 6 decimal digits and no padding (may vary depending on computer system). The formatted double placeholder has this format: %w.df, where w is the total width of the field (including sign and decimal point) and d the number of decimal digits. If the value is 4.56 and the placeholder is %6.3f, then the display will be _4.560 One leading blank

78 Floating Point Placeholders
With a floating point formatted print, you always get the requested number of decimal digits (even if the field is not wide enough). You also always (like the integer placeholder) get all the significant numbers. However, if there are more decimal precision in the value than in the placeholder, the value is truncated and rounded up if need be.

79 Floating Point Placeholders
If the value is and the placeholder is %7.3f, then you will get 3 decimal digits as requested plus the significant numbers: If the value is and the placeholder is %8.3f, then you will get 3 decimal digits as requested plus the significant numbers and padding: _ See the rounding-up effect. A %8.7f for a value of will produce a display of Note: Internal values in the computer's memory are unaffected by placeholders (see workspace). space

80 Common conversion specifiers
The fprintf Command Conversion specifier >> fprintf( 'Joe weighs %f kilos', n1 ) Common conversion specifiers %f fixed point (decimal always between 1's and 0.1's place, e.g., 3.14, 56.8 %e scientific notation, e.g, 2.99e+008 %d integers (no decimal point shown) %s string of characters

81 The fprintf Command >> fprintf( 'Joe weighs %6.2f kilos', n1 ) To control display in fixed or scientific, use %w.pf or %w.pe w = width: the minimum number of characters to be displayed p = “precision”: the number of digits to the right of the decimal point If you omit "w", MATLAB will display correct precision and just the right length T I P

82 The %e placeholder – Scientific Notation
%e works like %f Here are a few examples: >> z = exp(1); %the value of the constant e is put into variable z >> fprintf( 'z is %f\n', z ) e is about >> fprintf( 'z is %10.8f\n', z ) e is about >> fprintf( 'z is %10.8e', z ) e is about e+000 >> fprintf( 'z is %10.2e', z ) e is about 2.72e+000

83 fprintf( format, n1, n2, n3 ) The fprintf Command Argument
>> fprintf( 'Joe weighs %6.2f kilos', n1 ) Argument Conversion specifier (placeholder) Example: Joe weighs kilos

84 Number of arguments and conversion specifiers must be the same
The fprintf Command >> fprintf( 'Joe is %d, weighs %f kilos', age, weight ) Arguments Number of arguments and conversion specifiers must be the same Leftmost conversion specifier formats leftmost argument, 2nd to left specifier formats 2nd to left argument, etc.

85 The fprintf Command Make the following strings: Mom's apple 3.14
Mom's apple 3.1e+000 >> fprintf( 'Mom''s apple %.2f\n', pi ) >> fprintf( 'Mom''s apple %.7f\n', pi ) Mom's apple >> fprintf( 'Mom''s apple %.1e\n', pi )

86 Example The fprintf Command The fprintf Command
>> weight = 178.3; >> age = 17; >> fprintf( ['Tim weighs %.1f lbs'... ' and is %d years old'], weight, age ) Tim weighs lbs and is 17 years old


Download ppt "Using Script Files and Managing Data"

Similar presentations


Ads by Google