0% found this document useful (0 votes)
87 views52 pages

Computer Applications in Metallurgical Industries

This document discusses various file types and functions used in MATLAB for metallurgical applications. It describes how M-files store MATLAB programs and functions, MAT-files save variables, and ASCII data files store experimental data. Functions for saving and loading workspaces, directories, and paths are also covered. The document then discusses MATLAB's ability to handle arrays and matrices, perform mathematical operations on them, find polynomial roots, and create different plot types including subplots.
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)
87 views52 pages

Computer Applications in Metallurgical Industries

This document discusses various file types and functions used in MATLAB for metallurgical applications. It describes how M-files store MATLAB programs and functions, MAT-files save variables, and ASCII data files store experimental data. Functions for saving and loading workspaces, directories, and paths are also covered. The document then discusses MATLAB's ability to handle arrays and matrices, perform mathematical operations on them, find polynomial roots, and create different plot types including subplots.
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/ 52

Cairo University

Faculty of Engineering
Mining, Petroleum and Metallurgy Department
4th Year Metallurgy

Computer Applications in
Metallurgical Industries
LECTURE 2
By Dr. Ahmed Hatem Al-Khoribi
• Working with Files
• MATLAB uses several types of files that enable
you to save programs, data, and session results.
MATLAB function files and program files are
saved with the extension .m, and thus are called
M-files. MAT-files have the extension .mat and
are used to save the names and values of
variables created during a MATLAB session.

• Because they are ASCII files, M-files can be


created using just about any word processor.
MAT-files are binary files that are generally
readable only by the software that created them.
MAT-files contain a machine signature that allows
them to be transferred between machine types
such as MS Windows and Macintosh machines.
• The third type of file we will be using is a data
file, specifically an ASCII data file, that is, one
created according to the ASCII format. You
may need to use MATLAB to analyze data
stored in such a file created by a spreadsheet
program, a word processor, or a laboratory
data acquisition system or in a file you share
with someone else.
• Saving and Retrieving Your Workspace Variables
• If you want to continue a MATLAB session at a later time,
you must use the save and load commands. Typing save
causes MATLAB to save the workspace variables, that is, the
variable names, their sizes, and their values, in a binary file
called matlab.mat, which MATLAB can read. The file is
saved in the current directory. To retrieve your workspace
variables, type load. But, the current directory must
contain the requested file otherwise the load command will
return an error message. You can then continue your
session as before.

• To save the workspace variables in another file named


filename.mat, type save filename. To load the workspace
variables, type load filename. If the saved MAT-file
filename contains the variables A, B, and C, then loading
the file filename places these variables back into the
workspace and overwrites any existing variables having the
same name.
• Directories and Path
• It is important to know the location of the files you use
with MATLAB. File location frequently causes problems
for beginners. Suppose you use MATLAB on your home
computer and save a file to a removable disk. If you
bring that disk to use with MATLAB on another
computer, say, in a school’s computer lab, you must
make sure that MATLAB knows how to find your files.
Files are stored in directories, called folders on some
computer systems. Directories can have subdirectories
below them.

• For example, suppose MATLAB was installed on drive c:


in the directory c:\matlab. Then the toolbox directory
is a subdirectory under the directory c:\matlab, and
symbolic is a subdirectory under the toolbox directory.
The path tells us and MATLAB how to find a particular
file.
• Mathematical Functions

|x| abs (x)


sin-1 x (answer in degrees) asind (x)
• Arrays
• MATLAB has hundreds of functions, which we
will discuss throughout the text. For example,
to compute sin x, where x has a value in
radians, you type sin(x). To compute cos x, type
cos(x). The exponential function ex is computed
from exp(x). The natural logarithm, ln x, is
computed by typing log(x). You compute the
base-10 logarithm by typing log10(x). The
inverse sine, or arcsine, is obtained by typing
asin(x). It returns an answer in radians, not
degrees. The function asind(x) returns degrees.
• One of the strengths of MATLAB is its ability to
handle collections of numbers, called arrays, as if
they were a single variable. A numerical array is
an ordered collection of numbers (a set of
numbers arranged in a specific order). An example
of an array variable is one that contains the
numbers 0, 4, 3, and 6, in that order.
• We use square brackets to define the variable x to
contain this collection by typing x = [0, 4, 3, 6]. The
elements of the array may also be separated by
spaces, but commas are preferred to improve
readability and avoid mistakes. Note that the
variable y defined as y = [6, 3, 4, 0] is not the same
as x because the order is different.
• The reason for using the brackets is as follows.
If you were to type x = 0, 4, 3, 6, MATLAB
would treat this as four separate inputs and
would assign the value 0 to x. The array [0, 4, 3,
6] can be considered to have one row and four
columns, and it is a sub case of a matrix, which
has multiple rows and columns. As we will see,
matrices are also denoted by square brackets.
• We can add the two arrays x and y to produce
another array z by typing the single line z = x + y.
To compute z, MATLAB adds all the
corresponding numbers in x and y to produce z.
The resulting array z contains the numbers 6, 7,
7, 6. You need not type all the numbers in the
array if they are regularly spaced. Instead, you
type the first number and the last number , with
the spacing in the middle, separated by colons.
For example, the numbers 0, 0.1, 0.2, . . . , 10
can be assigned to the variable u by typing u =
0:0.1:10. In this application of the colon
operator, the brackets should not be used.
• To compute w=5*sin u for u 0, 0.1, 0.2 , . . . ,
10, the session is
>> u = 0:0.1:10;
>> w = 5*sin(u);
• The single line w = 5*sin(u) computed the
formula w=5*sin u 101 times, once for each
value in the array u, to produce an array w that
has 101 values. You can see all the u values by
typing u after the prompt; or, for example, you
can see the seventh value by typing u(7). The
number 7 is called an array index, because it
points to a particular element in the array.
• Note: Arrays created using (:) are row arrays.
>> u(7)
ans =
0.6000
>> w(7)
ans =
2.8232
• You can use the length function to determine how many
values are in an array. For example, continue the
previous session as follows
>> m = length(w)
m=
101
• Arrays that display on the screen as a single row of
numbers with more than one column are called row
arrays. You can create column arrays, which have more
than one row, by using a semicolon to separate the
rows.
• Polynomial Roots

• We can describe a polynomial in MATLAB with an


array whose elements are the polynomial’s
coefficients, starting with the coefficient of the
highest power of x.

• For example, the polynomial 4x3-8x2+7x-5 would


be represented by the row array [4,-8,7,-5]. The
roots of the polynomial f (x) are the values of x
such that f (x)=0. Polynomial roots can be found
with the roots(a) function, where a is the
polynomial’s coefficient array. The result is a
column array that contains the polynomial’s roots.
• For example, to find the roots of x3-7x2 + 40x -
34= 0, the session is
>> a = [1,-7,40,-34];
>> roots(a)
ans =
3.0000 + 5.000i
3.0000 - 5.000i
1.0000
• The roots are x=1 and x=35i. The two
commands could have been combined into the
single command roots([1,-7,40,-34]).
• Plotting with MATLAB
• MATLAB contains many powerful functions for
easily creating plots of several different types,
such as rectilinear (consisting of straight lines),
logarithmic, surface, and contour plots. As a
simple example, let us plot the function
y = 3 cos 2x for 0  x 7. We choose to use an
increment of 0.01 to generate a large number
of x values in order to produce a smooth curve.
The function plot(x,y) generates a plot with the
x values on the horizontal axis (the abscissa)
and the y values on the vertical axis (the
ordinate).
• The session is
>> x = 0:0.01:7;
>> y = 3*cos(2*x);
>> plot(x,y), xlabel(‘x’), ylabel(‘y’)

• The plot appears on the screen in a graphics


window, named Figure 1, as shown in figure. The
xlabel function places the text that is written in
single quotes as a label on the horizontal axis. The
ylabel function performs a similar function for the
vertical axis. When the plot command is
successfully executed, a graphics window
automatically appears. If a hard copy of the plot is
desired, the plot can be printed by selecting Print
from the File menu on the graphics window OR by
pressing Ctrl+P.
• The window can be closed by selecting Close
on the File menu in the graphics window OR by
pressing Ctrl+W. You will then be returned to
the prompt in the Command window.
• Other useful plotting functions are title and
gtext. These functions place text on the plot.
Both accept text within parentheses and single
quotes, as with the xlabel function. The title
function places the text at the top of the plot;
the gtext function places the text at the point
on the plot where the cursor is located when
you click the left mouse button.
• Plotting Commands
• Types of Plots
1. Subplots.
2. Overlay Plots.
3. Logarithmic Plots.
4. Stem, Stairs, and Bar Plots.
• Subplots
• You can use the subplot command to obtain
several smaller subplots in the same figure. The
syntax is subplot(m,n,p). This command divides
the Figure window into an array of rectangular
panes with m rows and n columns.
• The variable p tells MATLAB to place the output of
the plot command following the subplot command
into the pth pane. For example, subplot(3,2,5)
creates an array of six panes, three panes deep
and two panes across, and directs the next plot to
appear in the fth pane (in the bottom left corner).
The following session created a figure, which
shows the plots of the functions y=3x for 5  x  8,
y=sin x for -2  x  10, and y=e|2x| for -3  x  6.
>> x = 5:0.01:8;
>> y = 3*x;
>> subplot(1,3,1), …
plot(x,y), xlabel(‘x’), ylabel(‘y’), …
x = -2:0.01:10; …
y = sin(x); …
subplot(1,3,2), …
plot(x,y), xlabel(‘x’), ylabel(‘y’), …
x = -3:0.01:6; …
y = exp(abs(2*x)); …
subplot(1,3,3), …
plot(x,y), xlabel(‘x’), ylabel(‘y’)
• Note: The previous code consists only of THREE lines.
• Overlay Plots
• You can create multiple curves on a single plot,
called overlay plot, by including another set or sets
of values in the plot function. For example, to plot
the functions y = 2x and z = 4sin 3x for 0  x  5
on the same plot, the session is
>> x = 0:0.01:5;
>> y = 2*sqrt(x);
>> z = 4*sin(3*x);
>> plot(x,y,x,z), xlabel(‘x’), gtext(‘y’), gtext(‘z’)
• After the plot appears on the screen, the program
waits for you to position the cursor and click the
mouse button, once for each gtext function used.
• Use the gtext function to place the labels y and
z next to the appropriate curves.
• Sometimes it is useful or necessary to obtain
the coordinates of a point on a plotted curve.
The function ginput can be used for this
purpose. Place it at the end of all the plot and
plot formatting statements, so that the plot will
be in its final form. The command [x, y] =
ginput(n) gets n points and returns the x and y
coordinates in the vectors x and y, which have a
length n. Position/place the cursor using a
mouse, and press the mouse button. The
returned coordinates have the same scale as
the coordinates on the plot.
• Consider the previous example, the function
ginput can be added to the plot command line
in order to return the x and y coordinates of six
points on the plotted curve. The session is
>> x = 0:0.01:5;
>> y = 2*sqrt(x);
>> z = 4*sin(3*x);
>> plot(x,y,x,z), xlabel(‘x’), gtext(‘y’), gtext(‘z’), …
ginput(6)
• The last command line can also be as follows
>> plot(x,y,x,z), xlabel(‘x’), gtext(‘y’), gtext(‘z’), …
[e,r] = ginput(6)
• In cases where you are plotting measured data,
as opposed to functions, you should use data
markers to plot each data point (unless there
are very many data points). To mark each point
with a plus sign , the required syntax/marker
for the plot function is plot(x,y,’+’). Common
syntaxes are +, ^, *, and o. You can connect the
data points with lines if you wish. In that case,
you must plot the data twice, once with a data
marker and once without a marker.
• For example, suppose the data for the
independent variable is x = [15:2:23] and the
dependent variable values are y = [20, 50, 60,
90, 70]. To plot the data with plus signs, use
the following session:
>> x = 15:2:23;
>> y = [20, 50, 60, 90, 70];
>> plot(x,y,’+’,x,y), xlabel(‘x’), ylabel(‘y’), grid
• The grid command puts grid lines on the plot.
• All plotting commands must be placed after
the plot command.
• You can also plot the data just one time where
both the marker and the line type are
combined together in single quotes.
>> plot(x,y,’+’,x,y)
is equivalent to
>> plot(x,y,’+-’)
• But, in the first plot command, plot is executed
twice while in the second plot command, plot
is executed once. This explains the appearance
of two different colors of the marker and the
line in the figure when using the first command
and the appearance of a single color of both of
them when using the second command.
• Exercise:
• Execute the following commands:
>> x = 15:2:23;
>> y = [20, 50, 60, 90, 70];
>> z = 2*x;
>> plot(x,y,’r+’, x,y,’g--‘, x,z,’ko’, x,z,’y:’)
>> plot(x,y,’r+--‘, x,z,’k*’, x,z,’y-’)
>> plot(x,y,’g+--’, x,y,’r.-’, x,z,’k^-’)
>> plot(x,y,’g+--’, x,y,’r.-’, x,y,’ms’, x,z,’k^’, x,z,’b*-’)
>> plot(x,y,’g+-’, x,y,’r.--’, x,y,’ms’, x,z,’k^’, x,z,’b*-’)
>> plot(x,y,’r.-’, x,y,’g+--’, x,y,’ms’, x,z,’k^’, x,z,’b*-’)
• Note:
• A single quote cannot handle two or more
commands of the same type such as two
colors, two data markers, or two line types.
• The following plot commands are going to
generate error messages if executed.
>> plot(x,y,’r+’, x,y,’gb--‘, x,z,’ko’, x,z,’y:’)
>> plot(x,y,’r+^--‘, x,z,’k*’, x,z,’y-’)
>> plot(x,y,’g+--:’, x,y,’r.-’, x,z,’k^-’)
• The following table shows data markers, line
types, and colors that can be used to
distinguish overlay plots.
• Labeling Curves and Data
• When more than one curve or data set is plotted
on a graph, we must distinguish between them. If
we use different data symbols or different line
types, then we must either provide a legend or
place a label next to each curve.
• To create a legend use the legend command. The
basic form of this command is legend
(‘string1’,‘string2’), where string1 and string2 are
text strings of your choice. The legend command
automatically obtains from the plot the line type
used for each data set and displays a sample of
this line type in the legend box next to the string
you selected. The following session produced the
plot shown in figure.
>> x = 0:0.01:2;
>> y = sinh(x);
>> z = tanh(x);
>> plot(x,y, x,z,‘--’), xlabel(‘x’),...
ylabel(‘Hyperbolic Sine and Hyperbolic…
Tangent’),...
legend(‘sinh(x)’,’tanh(x)’)
• hold all Command
• The hold all command creates a plot that needs
two or more plot commands.
• Suppose we want to plot y1 = x, y2 = 2x, and y3
= 10x for 3  x  9 on the same plot. The session
will be
>> x = 3:0.01:9;
>> y1 = x;
>> y2 = 2*x;
>> y3 = 10*x;
>> plot(x,y1), hold all, plot(x,y2), plot(x,y3)
• An equivalent code can be as follows
>> x = 3:0.01:9;
>> y = x;
>> plot(x,y), hold all, plot(x,2*y), plot(x,10*y)
• The first plot command will draw x vs. y. The y-
axis equals y.
• The second plot command will draw x vs. 2y.
The y-axis equals 2y.
• The third plot command will draw x vs. 10y. The
y-axis equals 10y.
• Note: The variable y has never changed. Then, y
still equals x.
• text Command
• The text command places the string text in the
Figure window at a point specified by
coordinates x, y.
• Suppose we want to add 3 texts to the previous
3 curves. The last command line shall be
modified as follows

>> plot(x,y1), text(5,80,’Alpha’), hold all, ...


plot(x,y2), text(7,30,’Beta’), plot(x,y3), ...
text(7.5,4,’Gamma’)
• Logarithmic Plots
• Logarithmic scales-abbreviated log scales-are
widely used (1) to represent a data set that
covers a wide range of values and (2) to
identify certain trends in data.
• Certain types of functional relationships
appear as straight lines when plotted using a
log scale. This method makes it easier to
identify the function. A log-log plot has log
scales on both axes. A semilog plot has a log
scale on only one axis.
• Consider the following example:
>> t = 7:1:12;
>> r = [1e-2, 1e-1, 1e0, 0.8e1, 4e2, 20e3];
>> semilogy(t,r), xlabel(‘t’), ylabel(‘r’)

• Note:
• 1e-2=1*10-2
• 0.8e1=0.8*101
• 20e3=20*103
• Stem, Stairs, and Bar Plots
• MATLAB has several other plot types that are
related to xy plots. These include the stem,
stairs, and bar plots. Their syntax is very
simple, namely, stem(x,y), stairs(x,y), and
bar(x,y).
• Consider the following session:
>> u = [1, 2, 3, 4];
>> k = [4, 6, 10, 3];
>> bar(u,k)
• Separate y Axes
• The plotyy function generates a graph with two y
axes. The syntax plotyy (x1,y1,x2,y2) plots y1
versus x1 with y axis labeling on the left, and
plots y2 versus x2 with y axis labeling on the
right.
• The syntax plotyy(x1,y1,x2,y2,’type1’,’type2’)
generates a ‘type1’ plot of y1 versus x1 with y
axis labeling on the left, and generates a ‘type2’
plot of y2 versus x2 with y axis labeling on the
right.
• For example, plotyy(x1,y1,x2,y2,‘plot’,‘stem’) uses
plot(x1,y1) to generate a plot for the left axis, and
stem(x2,y2) to generate a plot for the right axis.
To see other variations of the plotyy function,
type help plotyy.
• grid and axis Commands
• The grid command displays gridlines at the
tick marks corresponding to the tick labels.
You can use the axis command to override the
MATLAB selections for the axis limits. The
basic syntax is axis([xmin xmax ymin ymax]).
• This command sets the scaling for the x and y
axes to the minimum and maximum values
indicated. Note that, unlike an array, this
command does not use commas to separate
the values.
• The axis command has the following variants:
• axis square selects the axes’ limits so that the
plot will be square.
• axis equal selects the scale factors and tick
spacing to be the same on each axis. This
variation makes plot(sin(x),cos(x)) look like a
circle, instead of an oval.
• axis auto returns the axis scaling to its default
auto scaling mode in which the best axes’
limits are computed automatically.
• trapz Command
• trapz command can be used to apply trapezoidal
rule to a curve in order to calculate the area
under it. Consider the following session:
>> x = [7,8,10,15,50];
>> T = 2*x;
>> Area_under_curve = trapz(x,T)
Area_under_curve =
2451
• You cannot directly specify a function to integrate
with the trapz function; you must first compute
and store the function’s values ahead of time in
an array.
• polyxpoly Command
• polyxpoly command can be used to find
intersection points of two curves and return their
x and y coordinates. Consider the following
session:
>> x1 = 1:0.1:9;
>> y1 = 20*x1;
>> x2 = 1:0.1:9;
>> y2 = 2*x2+100;
>> [x,y] = polyxpoly(x1,y1,x2,y2)
x=
5.5556
y=
111.1111
• Plotting Polynomials
• We can plot polynomials more easily by using the
polyval function. The function polyval(p,x) evaluates
the polynomial p at specified values of its independent
variable x. For example, to plot the polynomial 3x5 +
2x4 - 100x3 + 2x2 - 7x + 90 over the range - 6  x  6
with a spacing of 0.01, you type
>> x = -6:0.01:6;
>> p = [3,2,-100,2,-7,90];
>> plot(x, polyval(p,x)), xlabel(‘x’), ylabel(‘f(x)’)
OR
>> x = -6:0.01:6;
>> p = [3,2,-100,2,-7,90];
>> f = polyval(p,x);
>> plot(x, f), xlabel(‘x’), ylabel(‘f(x)’)
• Exporting/Saving Figures
• If you want to save the figure in a format that
can be used by another application, such as
the standard graphics file formats BMP, TIFF,
or EPS, perform these steps.
1. Select Export Setup from the File menu. This
dialog provides options you can specify for the
output file, such as the figure size, fonts, line
size and style, and output format.
2. Select Export from the Export Setup dialog. A
standard Save As dialog appears.
3. Select the format from the list of formats in
the Save As type menu. This selects the
format of the exported file and adds the
standard file name extension given to files of
that type.
4. Enter the name you want to give the file, less
the extension.
5. Click Save.

You might also like