Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
34 views78 pages

Lecture 3 ManageData Plots

This document discusses strings and string variables in MATLAB. It explains that strings are arrays of characters that are defined within single quotes. Strings can be assigned to variables and each character is an element in the array. The document also covers using the input command to take user input as strings or numeric values, and the disp and fprintf commands for outputting text and variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views78 pages

Lecture 3 ManageData Plots

This document discusses strings and string variables in MATLAB. It explains that strings are arrays of characters that are defined within single quotes. Strings can be assigned to variables and each character is an element in the array. The document also covers using the input command to take user input as strings or numeric values, and the disp and fprintf commands for outputting text and variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Computational Methods in

Chemical Engineering

LECTURE 3
MANAGING DATA, PLOTTING IN
MATLAB

ÖZGE KÜRKÇÜOĞLU-LEVİTAS
Strings and Strings As Variables

 String is an array of characters. It is created by typing the characters within


single quotes.
 Strings can include letters, digits, other symbols, and spaces.
 A string that contains a single quote is created by typing two single quotes
within the string.
 When a string is being typed in, the color of the string changes to purple.

 Strings have several different uses in MATLAB.


 They are used in output commands to display text messages, in formatting
commands of plots, and as input arguments of some functions.
Strings and Strings As Variables

 Strings can also be assigned to variables by simply typing the string on the
right side of the assignment operator,
 When a variable is defined as a string, the characters of the string are stored in
an array just as numbers are.
 Each character, including a space, is an element in the array. This means that a
one-line string is a row vector in which the number of elements is equal to the
number of characters.
 As with a vector that contains numbers, it is also possible to change specific
elements by addressing them directly.
Strings and Strings As Variables

 MATLAB has a built-in function named “char” that creates an array


with rows having the same number of characters from an input of rows
not all of the same length.

 MATLAB makes the length of all the rows equal to that of the longest
row by adding spaces at the end of the short lines.
 In the char function, the rows are entered as strings separated by a
comma according to the following format.

variable_name = char('string 1', 'string 2', 'string 3')


>> c = 'A' >> k = ['Albert ', 'Einstein']
c= k=
A Albert Einstein
>> size(k)
>> s = 'ABC DEFG'
ans =
%row vector of 8
1 15
characters
s=
ABC DEFG
-

>>s(2), s(3:5)
ans =
B
ans =
CD
W

>>s(4)
ans =
>> k=['reactor ';'distillation']

k= 6
Both strings should
have same size
2×12 char array

'reactor '
'distillation‘

>> A=char('reactor','distillation')

A=

2×12 char array

'reactor ' Also try


'distillation' strvcat(‘aa’,’bb’)
a = [143.87, -0.0000325, -7545]';
>> s = num2str(a)
s= 7
143.87
-3.25e-005
-7545

Also try:
>> s = num2str(a,4); % define number of digits
>> s = num2str(a, '%12.6f'); % define a format
Useful string functions
8

sprintf -write formatted string


sscanf -read formatted string
deblank -remove trailing blanks
strmatch -find possible matches
upper -convert to upper case
lower -convert to lower case
blanks -string of blanks
strjust -left/right/center justify string
strtrim -remove leading/trailing spaces
strrep -replace strings
findstr -find one string within another
Input to a Script File
 A script file is opened by clicking New > Script
In this lecture
notes, this color
indicates an
mfile
 When a script file is executed:
 Variables used in calculations must have assigned values
 They must be in workspace!

 It can be done in three ways


 Depending on where and how variable is defined
10

1-Variable is defined & assigned a value in script file


 You assign a value to the variable in the script file

 If user wants to run file with a different variable value


 File must be edited:
 Assign a new value to the variable

 After file is saved


 It can be executed again
 Example:
 Calculate the average points scored in three games
11

2-Variable is defined & assigned a value in Command Window


 Assignment of a value to the variable is done in the Command
Window
 If user wants to run script file with a different value
 New value is assigned in the Command Window

 File is executed again


12

3-Variable is defined in script file, but a specific value is entered in


Command Window when script file is executed
 Variable is defined in script file
 When the file is executed,
 User is prompted to assign a value to variable in Command
Window.
 Done by using “input” command for creating the variable
variable_name = input( ' message in Command Window ' )

 User types the value and presses Enter key


 This assigns the value to the variable
13

 Variable and its assigned value will be displayed in Command


Window
 Unless a semicolon is typed at the end of input command

 Besides scalars,
 Vectors and arrays can also be assigned.
 Done by typing array in the same way that it is usually
assigned to a variable
 (left bracket, then typing row by row, and a right bracket).
prompt = 'What is the original value? ';
x = input(prompt) mfile
y = x*10

Run your script!


At the prompt, enter a numeric value or array, such as 42.
>>x =
42
>>y =
420

At the prompt, enter magic(3).


>>x =
816 At the prompt, enter a matrix.
357 >>x =
492 [1 2; 3 4] % remember the [ ]
>>y =
>>y = 10 20
80 10 60 30 40
30 50 70
40 90 20
15

 Input command can also be used to assign a string to a variable


 Done in one of two ways:
1. Use command in the same form as discussed above
 When prompt message appears
 Type string between two single quotes
2. Use an option in input command that defines the characters
that are entered as a string.
 The form of command:
variable_name = input ( ' message ' , ' s ' )
 ‘s’ inside command defines the characters
 That will be entered as a string.
name = input('what is your name: ', 's');
disp(‘your name is: ’);
disp(name)
Run your script!
At the command window:

what is your name: Zeynep


your name is
Zeynep

name = input('what is your name: ');


disp(‘your name is: ’);
disp(name)
Run your script!
At the command window:

what is your name: ‘Zeynep’


your name is
Zeynep
Output Command
17

 Two commands frequently used:


 disp
 Displays output on screen

 fprintf
 Display output on screen
 Save output to a file

>> help iofun %get help for input/output functions


disp
18

1. Used to display the elements of a variable


 Without displaying name of variable

2. Used to display text


Syntax:
disp(variable) and disp(' text as string ' )

 Only one variable can be displayed in a disp command


 If elements of two variables need to be displayed together
 New variable must be defined & displayed
19

 Display output (numbers) in a table


 Can be done by
 First defining a variable that is an array with the numbers
 Then using disp command to display the array.

 Headings to columns can also be created with disp command


 In the disp command
 User cannot control the format (the width of the columns and
the distance between the columns) of the display of the array,
 Position of the headings has to be aligned with the columns by
adding spaces.
A = [15 150];
S = 'Hello World.';
Run your script!
disp(A)
15 150

disp(S)
Hello World

X = rand(5,3);
disp(' Corn Oats Hay')
disp(X)
Run your script!
Corn Oats Hay
0.8147 0.0975 0.1576
0.9058 0.2785 0.9706
0.1270 0.5469 0.9572
0.9134 0.9575 0.4854
0.6324 0.9649 0.8003
name = 'Alice';
age = 12;
X = [name,' will be ',num2str(age),' this year.'];
disp(X)
Run your script!
>> Alice will be 12 this year.
fprintf
22

 Used to display output (text and data) on screen or to save it to a


file
 Output can be formatted.

 For example,
 Text and numerical values of variables can be intermixed and
displayed in the same line.
 Format of the numbers can be controlled.
23

Using the fprintf command to display text:


 To display text, fprintf command has the form
fprintf('text typed in as a string')

 With fprintf command


 It is possible to start a new line in the middle of the string.
 Done by inserting \n before the character that will start new
line
 \n is called an escape character
24

 Other escape characters:


 \b Backspace
 \t Horizontal tab

 To start a new line with the “fprintf” command,


 \n must be typed at the start of the string
25

Using the fprintf command to display a mix of text and numerical


data:
 To display text and number, fprintf command has the form
fprintf('text as string %-5.2f additional text', var_name)

Spot where number is Formatting Name of variable


inserted within text elements whose value is
displayed
 Formatting elements: -5.2f

Flag Field width Conversion


(optional) & precision character
(optional) (required)
% convert double-precision values with fractions to integer values.
a = [1.02 3.04 5.06];
fprintf('%d\n',round(a));

>>
1
3
5
Flag
27

fprintf('text as string %-5.2f additional text', var_name

 The flag, which is optional, can be one of the following three


characters:
Character used for flag Description
– (minus sign) Left-justifies the number within the field
+ (plus sign) Prints a sign character (+ or –) in front of the number.
0 (zero) Adds zeros if the number is shorter than the field
Field width & precision
28

fprintf('text as string %-5.2f additional text', var_name

 Field width and precision (eg. 5.2) are optional


 First number (eg. 5) is the field width
 Which specifies the minimum number of digits in the display

 If the number to be displayed is shorter than the field width


 Spaces or zeros are added in front of the number

 Precision is the second number (eg. 2).


 It specifies the number of digits to be displayed to the right of
decimal point
Conversion character
29

 Last element in the formatting elements:


 specifies the notation in which the number is displayed.

 Some of the common notations are:


e Exponential notation using lower-case e (e.g., 1.709098e+001)
E Exponential notation using upper-case E (e.g., 1.709098E+001
f Fixed-point notation (e.g., 17.090980)
g The shorter of e or f notations
G The shorter of E or f notations
i Integer
30

%10.6f % width 10, 6 decimal places


% 10.6f % leave space before field
%-10.6f % left-justify field
%+10.6f % print + or –signs
%10.0f % no decimals

314.159265
314.159265
314.159265
+314.159265
314
31

 With “fprintf” command it is possible to insert more than one


number (value of a variable) within text
 This is done by typing “%” followed by any formatting elements
at the places in the text
 Where the numbers are to be inserted

 Then, after the string argument of the command (following the


comma),
 Names of the variables are typed in the order in which they are
inserted in the text
fprintf('..text...%g...%g...%f... ',var1,var2,var3)
%Print multiple numeric values and literal text to the screen
A1 = [9.9, 9900];
formatSpec = 'X is %4.2f meters or %8.3f mm\n';
fprintf(formatSpec,A1)

>> X is 9.90 meters or 9900.000 mm

%Print multiple numeric values and literal text to the screen


A1 = [9.9, 9900];
A2 = [8.8, 7.7; 8800, 7700];
formatSpec = 'X is %4.2f meters or %8.3f mm\n';
fprintf(formatSpec,A1,A2)

X is 9.90 meters or 9900.000 mm


X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm
33

Additional remarks about “fprintf” command:


 To place a single quotation mark in the displayed text
 Type two single quotation marks in the string inside the
command.
 “fprintf” command is vectorized.
 When a variable that is a vector or a matrix is included in the
command
 Command repeats itself until all the elements are displayed.
 If the variable is a matrix, the data is used column by column.
a = [1; -2; 3; 4;];
b = [10; 20; -30; 40];
c = [100; 200; 300; -400];
34 Merge a b c

!
fprintf('%9.3f %9.3f %9.3f\n', [a, b, c]');

1.000 10.000 100.000


-2.000 20.000 200.000
3.000 -30.000 300.000
4.000 40.000 -400.000

for i=1:4, % in loop version


fprintf('%9.3f %9.3f %9.3f\n', a(i),b(i),c(i));
end
>>a = [1; -2; 3; 4;];
>>b = [10; 20; -30; 40];
35
>>s =char('a','b','c','d');

>>for i=1:4; fprintf('%9.3f %9.3f %4s\n',a(i), b(i), s(i)); end


1.000 10.000 a
-2.000 20.000 b
3.000 -30.000 c
4.000 40.000 d
Using fprintf to save output to a file
36

 “fprintf” command can be used


 For writing the output to a file when it is necessary to save the
output.
 Data that is saved can subsequently be displayed or used in
MATLAB and in other applications.

 Writing output to a file requires three steps:


a) Opening a file using “fopen” command
b) Writing the output to the open file using the “fprintf” command

c) Closing the file using “fclose” command


Step a
37

 First a file must be opened.


 Done with “fopen” command,
 This creates a new file or opens an existing file.
“fopen” command has the form:
fid = fopen('file_name’, ‘permission')

 “fid” is a variable called “file identifier”.


 A scalar value is assigned to “fid” when “fopen” is executed.
 File name is written (including its extension) within single quotes
as a string.
 The permission is a code (also written as a string) that tells how
the file is opened.
38

 Some of the more common permission codes are:


r Open file for reading (default).
w Open file for writing. If the file already exists, its content is deleted.
If the file does not exist, a new file is created.
a Same as ‘w’, except that if the file exists the written data is appended to
the end of the file.
r+ Open file for reading and writing
read!ng
w+ & pen file for writing and writing. If the file already exists, its content is
-

deleted. If the file does not exists, a new file is created.


a+ Same as ‘w+’, except that if the file exists the written data is
appended to the
 If a permission code is not included in the command, file opens
with the default code ‘r’.
Step b & c
39

 Once the file is open, “fprintf” command can be used to write


output to file.
 “fprintf” command is used in exactly the same way as it is used to
display output in Command Window
 Except that the variable “fid” is inserted inside the command.
 “fprintf” command has the form:
fprintf(fid,'text %-5.2f additional text', var_name)
 When writing of data to the file is complete
 File is closed using “fclose” command

 “fclose” command has the form:


fclose(fid)
40

Additional notes
 The created file is saved in the current directory.
 It is possible to use “fprintf” command to write to several
different files.
 This is done by first opening the files, assigning a different
“fid” to each (e.g. fid1, fid2, fid3, etc.)
 Then using the “fid” of a specific file in “fprintf “command to
write to that file
% Write a short table of the exp function to a text file called exp.txt

x = 0:.1:1;
A = [x; exp(x)];

fileID = fopen('exp.txt','w');
fprintf(fileID,‘ x exp(x)\n'); %prints header
fprintf(fileID,'%6.2f %12.8f\n',A); %prints values
fclose(fileID);
save
42

 “save” command is used for saving the variables (all or some of


them) that are stored in the workspace.
 Two simplest forms of “save” command:
save file_name or save('file_name')
 When either one of these commands is executed,
 All variables currently in workspace are saved in a file named
file_name.mat that is created in current directory.

 These files cannot be read by other applications.


save
43

 “save” command can also be used for saving only some of the
variables that are in the workspace.
save file_name var1 var2 or save('file_name‘, ‘var1‘, ‘var2')

 “save” command can also be used for saving in ASCII format


 Which can be read by applications outside MATLAB
 Saving in ASCII format is done by adding the argument -ascii in
the command
 Note that the file does not include the names of variables just the
numerical values of the variables are listed
% Create and save two variables p, q to a file called pqfile.mat
p = rand(1,10);
q = ones(10);
save('pqfile.mat','p','q')

Or
save pqfile.mat p q

%Create two variables, save them to an ASCII file, and then


view the contents of the file
p = rand(1,10);
q = ones(10);
save('pqfile.txt','p','q','-ascii')
type('pqfile.txt')
Or
save pqfile.txt p q -ascii
load
45

 “load” command can also be used for retrieving only some of the
variables that are in the saved .mat file.
load file_name var1 var2 or load('file_name‘, ‘var1‘, ‘var2')
 “load” command can also be used to import data that is saved in
ASCII or text (.txt) to the workspace.
 This is possible,
 only if the data in the file is in the form of a variable in
MATLAB.
 Thus, the file can have one number (scalar), a row or a column
of numbers (vector), or rows with the same number of numbers
in each (matrix).
load
46

 When data is loaded from an ASCII or text file into the


workspace it has to be assigned to a variable name.
load file_name or VarName = load('file_name')
 If the data is in a text file, the extension .txt has to be added to the
file name.
load file_name.txt or VarName = load('file_name.txt')
 In the first form of the command the data is assigned to a variable
that has the name of the file.
 In the second form the data is assigned to a variable named
VarName
A=load(‘pqfile.txt’)
B=A(:,2)
load
48

 “load” command can be used for retrieving variables that were


saved with “save” command back to the workspace, and for
importing data that was created with other applications and saved
in ASCII format or in text (.txt) files.
 Variables that were saved with “save” command in .mat files can
be retrieved with the command:
load file_name and load('file_name')
 When command is executed, all variables in the file are added
(loaded back) to the workspace.
 If the workspace already has a variable with the same name
 Variable that is retrieved replaces the existing variable
Importing & Exporting Data
49

 MATLAB often used for analyzing data that was recorded in


experiments or generated by other computer programs.
 This can be done by first importing the data into MATLAB.
 Similarly, data that is produced by MATLAB sometimes needs to
be transferred to other computer applications.
 Here how to import and export numerical data is described.
 Importing data can be done either by using commands or by
using the Import Wizard.
 Commands are useful when the format of the data being
imported is known.
 Import Wizard is useful when the format of the data is not
known.
Commands
50

Importing and exporting data into and from Excel:


 Importing data from Excel is done with the “xlsread” command.
 When the command is executed, the data from the spreadsheet is
assigned as an array to a variable.
 The simplest form of the xlsread command is:
var_name = xlsread('file_name')
 ‘file_name’ (typed as a string) is the name of Excel file.
 The directory of the Excel file must be either the current directory
or listed in the search path.
 If the Excel file has more than one sheet, the data will be
imported from the first sheet.
51

 When an Excel file has several sheets, the xlsread command can
be used to import data from a specified sheet.
 The form of the command is then:
var_name = xlsread('file_name', 'sheet_name')
 The name of the sheet is typed as a string.
 Another option is to import only a portion of the data that is in
the spreadsheet.
 Done by typing an additional argument in command:
var_name = xlsread('file_name', 'sheet_name', 'range')
Import Wizard
52

• The MATLAB Import Wizard is the easiest way of importing data


into the workspace during an interactive session.
Importing text data
• Start the Import Wizard by selecting Import Data on the
MATLAB File menu. A list of files appears in a dialogue box.
Open the file you want to import.
• Select the delimiter used in the text file (if necessary). Click
Next.
• Select the variables you want to import. By default the Import
Wizard puts all the numeric data in one variable and all the text
data in other variables, but you can choose other options.
• Click Finish to import the data into the selected variables.
Import Wizard
53

Importing binary data


• Start it in the same way as when importing text data.
• When the file opens, the Import Wizard attempts to process its
contents and creates variables depending on the type of data in
the file.
• Check the variables you want to import and click Finish to create
the selected variables. You can, for example, import data from an
Excel spreadsheet in this way.
• If the data are numeric with row and column headers, the Import
Wizard imports the numeric data into a numeric array and the
headers into a cell array.
Two-Dimensional Plots
Simple Plot

• The xy plot is the most commonly used plot by engineers


– Independent variable usually called x
– Dependent variable usually called y
• Engineers always add
– Title
– x axis label, complete with units
– y axis label, complete with units
– Often it is useful to add a grid
Simple Plot

900

800

700

600

To plot the function


500

2x+5x 2
400

plot(xdata,ydata) 300

200

vector vector 100

0
0 2 4 6 8 10 12 14
time
Line, Color and Mark Style

 You can change the appearance of your plots by selecting user


defined
 line styles
 line color
 marker type
 If you don’t specify style, a default is used
 line style - none
 color - blue
 mark style – none
 Syntax
plot(xdata,ydata, 'line specifiers')
Property Name & Property Value

 You can specify


 thickness of line
 size of marker
 edge color of marker
 face color of marker
 size of font etc.
 Syntax:
plot(xdata,ydata, 'line specifiers', 'PropertyName', PropertyValue)
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));

figure plot(x,y,'--gs',...
'LineWidth',2,...
'MarkerSize',10,...
'MarkerEdgeColor','b',...
'MarkerFaceColor',[0.5,0.5,0.5])
Plot of a Given Data

Example:
 Sales data of a company

 Line specifier: dashed red line, asterisk marker


 Property values: line width is 2, marker size is 12

>>yr=1988:1994;
>>sales=[8 12 20 22 18 24 27];
>>plot(yr,sales,'r--*','Linewidth',2,'Markersize',12)
Plot of a Function

 In order to plot a function y = f(x) with plot command:


 Create a vector of values of x
 Create vector y with corresponding values of f(x) by using
element-by-element calculations
 Use them in plot command

Example:
 y = 3.5-0.5xcos(6x) for -2 ≤ x ≤ 4

>> x=linspace(-2,4,100);
>>y=3.5.^(-0.5*x).*cos(6*x);
>> plot(x,y,'-o')
fplot Command

 Plot a function with the form y = f(x) between specified limits


fplot('function', limits)
 function: Can be directly typed as a string inside the command.
 It can include MATLAB build-in functions and functions created
by users
 limits: Vector with two elements specifiying domain of x [xmin,
xmax] or four elements specifiying domain of x and limits of y
[xmin, xmax, ymin, ymax]
Example:
 y = 3.5-0.5xcos(6x) for -2 ≤ x ≤ 4

fplot(@(x) 3.5.^(-0.5*x).*cos(6*x),[-2,4])
Multiple Plots (plot command)

To plot both of these functions


on same graph with one command:
plot(x,y,x,z)
1

New figure should 0.8

0.6

pop up that looks 0.4

like following:
0.2

Each line defaults


-0.2

-0.4

to a different color -0.6

-0.8

-1
-4 -3 -2 -1 0 1 2 3 4
Multiple Plots (hold on/off command)

1 1

0.8 1stplot is 0.8 2nd plot is


0.6
drawn in blue 0.6
also blue
0.4 0.4

0.2 0.2

0 0

-0.2 -0.2

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8

-1 -1
-4 -3 -2 -1 0 1 2 3 4 -4 -3 -2 -1 0 1 2 3 4
x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure plot(x,y1,'g',x,y2,'b--o',x,y3,'c*')
Multiple Plots (line command)

 Major difference between plot and line commands:


 Plot starts a new plot every time it is executed
 Line adds graphs to a plot that exists.
line(x,y)
Multiple Plots

 MATLAB overwrites the figure window every time you


request a new plot
 To open new figure window, use “figure” function
 figure(2)
Formatting a Plot

 They may be entered after the plot or flot command


 xlabel & ylabel command:
xlabel('text as a string')
ylabel('text as a string')
 Title command:
title('text as a string')
 Text command:
text(x,y, 'text as a string') or gtext('text as a string')
 Legend command:
legend('sting1', 'string2',......, pos)
pos: optional number specify where legend is to be placed in figure
Formatting a Plot

 Subscript:
 Type _ in front of the character
 Superscript:
 Type ^ in front of the character

 Greek characters:
 Type \name of the letter within the string

 Grid command:
 Grid on: Adds grid lines to the plot

 Grid off: Removes grid lines from the plot


subplot
(1,2
satr volo
yahlı
Formatting a Plot

 Axis command
 MATLAB automatically scales each plot to completely fill
graph
 If you want to specify a different axis –

 Use the axis command


axis([xmin, xmax, ymin, ymax])
 Axis equal
 Axis square
 Axis tight
Logarithmic Axis Scaling

Command Name Plot type


plot(x,y) linear y vs linear x
loglog(x,y) log(y) (base 10) vs log(x) (base 10)
semilogx(x,y) y vs log(x) (base 10)
semilogy(x,y) log(y) (base 10) vs x
Subplots

 subplot command allows you to subdivide graphing


window into a grid of m rows and n columns:

A
subplot(m,n,p)

(3,2,1) (3,2,2)

(3,2,3) (3,2,4)

(3,2,5) (3,2,6)
Other Types of 2-D Plots

 Polar Plots: polar(x,y)


 Bar Graphs: bar(x,y)
 Pie Charts: pie(x)
 Histograms: hist(y)
 x-y graphs with 2 y axes: plotyy(x,y1,x,y2)
90 7%
1500
16%
120 60

1000 13%

150 30
500

180 0 30
7

26%
25
6

210 330
20 5

38%
240 300 4
270 15

10
2

5
1

0 0
1988 1989 1990 1991 1992 1993 1994 45 50 55 60 65 70 75 80 85 90 95
Closing Plots

 close: close the active Figure Window


 close(n): close the nth Figure Window
 close all: close all Figure Windows that are open
Saving Plots

 Save the figure from the “file” menu using the “save as…”
option
 You’ll be presented with several choices of file format such
as
 jpeg
 emg (enhanced metafile) etc

You might also like