5/30/2017 1 Lecture 2 Slide 1 EE 5303 Electromagnetic Analysis Using Finite‐Difference Time‐Domain Lecture #2 MATLAB Introduction and Graphics Lecture Outline Lecture 2 Slide 2 • MATLAB • Figures and handles • 1D plots • 2D graphics • Creating movies in MATLAB • String manipulation and text files • Helpful tidbits • Supplemental software This lecture is NOT intended to teach the basics of MATLAB. Instead, it is intended to summarize specific skills required for this course to a student already familiar with MATLAB basics and programming.
47
Embed
Lecture 2 -- MATLAB introduction and graphics - Home | EM Labemlab.utep.edu/ee5390fdtd/Lecture 2 -- MATLAB introduction and... · MATLAB Introduction and Graphics Lecture Outline
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
5302017
1
Lecture 2 Slide 1
EE 5303
Electromagnetic Analysis Using Finite‐Difference Time‐Domain
Lecture 2
MATLAB Introduction and Graphics
Lecture Outline
Lecture 2 Slide 2
bull MATLAB
bull Figures and handles
bull 1D plots
bull 2D graphics
bull Creating movies in MATLAB
bull String manipulation and text files
bull Helpful tidbits
bull Supplemental software
This lecture is NOT intended to teach the basics of MATLAB Instead it is intended to summarize specific skills required for this course to a student already familiar with MATLAB basics and programming
5302017
2
Lecture 2 Slide 3
MATLAB
Key MATLAB Concepts to Learn
Lecture 2 Slide 4
bull MATLAB interface
ndash Editor window vs command window
ndash Figure windows
bull MATLAB programming
ndash Scripts vs functions
ndash Variables and arrays
ndash Generating and manipulating arrays
ndash Basic commands for while if switch
ndash Basic graphics commands figure plot
5302017
3
Lecture 2 Slide 5
MATLAB Interface
MATLAB has three main components (1) command window (2) m‐file editor and (3) SimulinkWe will not use Simulink so we are only concerned withhellip
The command window is like a DOS prompt It can be used like a calculator here and you can also run programs you have written
The editor window lets you write edit and troubleshoot MATLAB programs
Lecture 2 Slide 6
My Preferred Dual‐Monitor Setup
On one monitor has my command and editor windows
I create full‐screen figure window on a second monitor for graphics and visualizations
This way I can see all the information at the same time
5302017
4
Lecture 2 Slide 7
Scripts Vs Functions
Script FilesInstead of typing all the commands at the command prompt you can type them into a text file and then run the code when you are done MATLAB behaves just like you typed the commands at the command prompt but scripts let you go back and edit what you have done
bull Script files share memory and variables with the command windowbull Unless you know better script files must be initializedbull Variables are easily accessed at the command prompt for troubleshooting
FunctionsPrograms can be written into functions so that they have defined inputs and outputs like the function y = cos(x) These do not share memory or variables with anything else except for what is defined at input or output
bull Functions do not share memory or variables with the command windowbull As far as the function knows memory is cleared when it is called except for the input
variablesbull You cannot access variables inside functions for troubleshootingbull Do not overwrite input arguments
File Names
bull File names cannot contain spaces
double matrixm should be double_matrixm
bull Functions are called by their filename not the name given in the code It is best practice to save the file with the same name as the given function name in the code
function y = dumbfunc(x) should be named dumbfuncm
Lecture 2 Slide 8
5302017
5
Lecture 2 Slide 9
How to Learn MATLAB
Tutorialsbull Search the internet for different tutorials
Be sure you know and can implement everything in this lecture
Practice Practice Practice
For Help in MATLAB
Lecture 2 Slide 10
bull The Mathworks website is very good
ndash httpwwwmathworkscomhelpmatlabindexhtml
bull Help at the command prompt
ndash ldquogtgt help commandrdquo
bull Dr Rumpfrsquos helpdesk
ndash rcrumpfutepedu
5302017
6
Lecture 2 Slide 11
Figures and Handles
Lecture 2 Slide 12
Graphics Handles
Every graphical entity in MATLAB has a handle associated with it This handle points to all their properties and attributes which can be changed at any time after the graphical entity is generated
Here h is the handle returned by these graphics calls
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
2
Lecture 2 Slide 3
MATLAB
Key MATLAB Concepts to Learn
Lecture 2 Slide 4
bull MATLAB interface
ndash Editor window vs command window
ndash Figure windows
bull MATLAB programming
ndash Scripts vs functions
ndash Variables and arrays
ndash Generating and manipulating arrays
ndash Basic commands for while if switch
ndash Basic graphics commands figure plot
5302017
3
Lecture 2 Slide 5
MATLAB Interface
MATLAB has three main components (1) command window (2) m‐file editor and (3) SimulinkWe will not use Simulink so we are only concerned withhellip
The command window is like a DOS prompt It can be used like a calculator here and you can also run programs you have written
The editor window lets you write edit and troubleshoot MATLAB programs
Lecture 2 Slide 6
My Preferred Dual‐Monitor Setup
On one monitor has my command and editor windows
I create full‐screen figure window on a second monitor for graphics and visualizations
This way I can see all the information at the same time
5302017
4
Lecture 2 Slide 7
Scripts Vs Functions
Script FilesInstead of typing all the commands at the command prompt you can type them into a text file and then run the code when you are done MATLAB behaves just like you typed the commands at the command prompt but scripts let you go back and edit what you have done
bull Script files share memory and variables with the command windowbull Unless you know better script files must be initializedbull Variables are easily accessed at the command prompt for troubleshooting
FunctionsPrograms can be written into functions so that they have defined inputs and outputs like the function y = cos(x) These do not share memory or variables with anything else except for what is defined at input or output
bull Functions do not share memory or variables with the command windowbull As far as the function knows memory is cleared when it is called except for the input
variablesbull You cannot access variables inside functions for troubleshootingbull Do not overwrite input arguments
File Names
bull File names cannot contain spaces
double matrixm should be double_matrixm
bull Functions are called by their filename not the name given in the code It is best practice to save the file with the same name as the given function name in the code
function y = dumbfunc(x) should be named dumbfuncm
Lecture 2 Slide 8
5302017
5
Lecture 2 Slide 9
How to Learn MATLAB
Tutorialsbull Search the internet for different tutorials
Be sure you know and can implement everything in this lecture
Practice Practice Practice
For Help in MATLAB
Lecture 2 Slide 10
bull The Mathworks website is very good
ndash httpwwwmathworkscomhelpmatlabindexhtml
bull Help at the command prompt
ndash ldquogtgt help commandrdquo
bull Dr Rumpfrsquos helpdesk
ndash rcrumpfutepedu
5302017
6
Lecture 2 Slide 11
Figures and Handles
Lecture 2 Slide 12
Graphics Handles
Every graphical entity in MATLAB has a handle associated with it This handle points to all their properties and attributes which can be changed at any time after the graphical entity is generated
Here h is the handle returned by these graphics calls
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
3
Lecture 2 Slide 5
MATLAB Interface
MATLAB has three main components (1) command window (2) m‐file editor and (3) SimulinkWe will not use Simulink so we are only concerned withhellip
The command window is like a DOS prompt It can be used like a calculator here and you can also run programs you have written
The editor window lets you write edit and troubleshoot MATLAB programs
Lecture 2 Slide 6
My Preferred Dual‐Monitor Setup
On one monitor has my command and editor windows
I create full‐screen figure window on a second monitor for graphics and visualizations
This way I can see all the information at the same time
5302017
4
Lecture 2 Slide 7
Scripts Vs Functions
Script FilesInstead of typing all the commands at the command prompt you can type them into a text file and then run the code when you are done MATLAB behaves just like you typed the commands at the command prompt but scripts let you go back and edit what you have done
bull Script files share memory and variables with the command windowbull Unless you know better script files must be initializedbull Variables are easily accessed at the command prompt for troubleshooting
FunctionsPrograms can be written into functions so that they have defined inputs and outputs like the function y = cos(x) These do not share memory or variables with anything else except for what is defined at input or output
bull Functions do not share memory or variables with the command windowbull As far as the function knows memory is cleared when it is called except for the input
variablesbull You cannot access variables inside functions for troubleshootingbull Do not overwrite input arguments
File Names
bull File names cannot contain spaces
double matrixm should be double_matrixm
bull Functions are called by their filename not the name given in the code It is best practice to save the file with the same name as the given function name in the code
function y = dumbfunc(x) should be named dumbfuncm
Lecture 2 Slide 8
5302017
5
Lecture 2 Slide 9
How to Learn MATLAB
Tutorialsbull Search the internet for different tutorials
Be sure you know and can implement everything in this lecture
Practice Practice Practice
For Help in MATLAB
Lecture 2 Slide 10
bull The Mathworks website is very good
ndash httpwwwmathworkscomhelpmatlabindexhtml
bull Help at the command prompt
ndash ldquogtgt help commandrdquo
bull Dr Rumpfrsquos helpdesk
ndash rcrumpfutepedu
5302017
6
Lecture 2 Slide 11
Figures and Handles
Lecture 2 Slide 12
Graphics Handles
Every graphical entity in MATLAB has a handle associated with it This handle points to all their properties and attributes which can be changed at any time after the graphical entity is generated
Here h is the handle returned by these graphics calls
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
4
Lecture 2 Slide 7
Scripts Vs Functions
Script FilesInstead of typing all the commands at the command prompt you can type them into a text file and then run the code when you are done MATLAB behaves just like you typed the commands at the command prompt but scripts let you go back and edit what you have done
bull Script files share memory and variables with the command windowbull Unless you know better script files must be initializedbull Variables are easily accessed at the command prompt for troubleshooting
FunctionsPrograms can be written into functions so that they have defined inputs and outputs like the function y = cos(x) These do not share memory or variables with anything else except for what is defined at input or output
bull Functions do not share memory or variables with the command windowbull As far as the function knows memory is cleared when it is called except for the input
variablesbull You cannot access variables inside functions for troubleshootingbull Do not overwrite input arguments
File Names
bull File names cannot contain spaces
double matrixm should be double_matrixm
bull Functions are called by their filename not the name given in the code It is best practice to save the file with the same name as the given function name in the code
function y = dumbfunc(x) should be named dumbfuncm
Lecture 2 Slide 8
5302017
5
Lecture 2 Slide 9
How to Learn MATLAB
Tutorialsbull Search the internet for different tutorials
Be sure you know and can implement everything in this lecture
Practice Practice Practice
For Help in MATLAB
Lecture 2 Slide 10
bull The Mathworks website is very good
ndash httpwwwmathworkscomhelpmatlabindexhtml
bull Help at the command prompt
ndash ldquogtgt help commandrdquo
bull Dr Rumpfrsquos helpdesk
ndash rcrumpfutepedu
5302017
6
Lecture 2 Slide 11
Figures and Handles
Lecture 2 Slide 12
Graphics Handles
Every graphical entity in MATLAB has a handle associated with it This handle points to all their properties and attributes which can be changed at any time after the graphical entity is generated
Here h is the handle returned by these graphics calls
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
5
Lecture 2 Slide 9
How to Learn MATLAB
Tutorialsbull Search the internet for different tutorials
Be sure you know and can implement everything in this lecture
Practice Practice Practice
For Help in MATLAB
Lecture 2 Slide 10
bull The Mathworks website is very good
ndash httpwwwmathworkscomhelpmatlabindexhtml
bull Help at the command prompt
ndash ldquogtgt help commandrdquo
bull Dr Rumpfrsquos helpdesk
ndash rcrumpfutepedu
5302017
6
Lecture 2 Slide 11
Figures and Handles
Lecture 2 Slide 12
Graphics Handles
Every graphical entity in MATLAB has a handle associated with it This handle points to all their properties and attributes which can be changed at any time after the graphical entity is generated
Here h is the handle returned by these graphics calls
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
6
Lecture 2 Slide 11
Figures and Handles
Lecture 2 Slide 12
Graphics Handles
Every graphical entity in MATLAB has a handle associated with it This handle points to all their properties and attributes which can be changed at any time after the graphical entity is generated
Here h is the handle returned by these graphics calls
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
7
Lecture 2 Slide 13
The Figure Window
All graphics are drawn to the active figure window There can be more than one
fig1 = figurefig2 = figure
figure(fig1)plot(x1y1)
figure(fig2)plot(x2y2) This code opens two figure windows with
handles fig1 and fig2 It then plots x1 vs y1 in the first figure window and x2 vs y2 in the second figure window It is possible to then go back to fig1 and anything else
Lecture 2 Slide 14
Investigating Graphics Properties (1 of 2)
To see all the properties associated with a graphics entity and their current values type get(h) at the command prompt
gtgt fig1 = figuregtgt get(fig1)
Alphamap = [ (1 by 64) double array]CloseRequestFcn = closereqColor = [08 08 08]Visible = on
To get the value of a single property
gtgt c = get(fig1Color)gtgt c
c =
08000 08000 08000
5302017
8
Lecture 2 Slide 15
Investigating Graphics Properties (2 of 2)
To see all the properties associated with a graphics entity and their possible values type set(h) at the command prompt
gtgt fig1 = figuregtgt set(fig1)
DockControls [ on | off ]IntegerHandle [ on | off ]InvertHardcopy [ on | off ]Visible [ on | off ]
The set() command is what is used to change graphics properties
gtgt set(fig1Colorr)
Lecture 2 Slide 16
Changing the Background Color
gtgt c = [10 08 00]gtgt set(fig1Colorc)
I almost exclusively use white as the background so that it is easier to paste the graphics in a paperpublication that has a white background
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
title($ textrmPlot of Function sin(x) textrm 0 leq x leq 2pi $InterpreterLaTexFontSize18)
Lecture 2 Slide 38
2D Graphics
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
20
Lecture 2 Slide 39
imagesc() (1 of 3)
The imagesc() command displays a 2D array of data as an image to the screen It automatically scales the coloring to match the scale of the data
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaDrsquo)
I use this function to display ldquodigital looking rdquo data from arrays
Lecture 2 Slide 40
imagesc() (2 of 3)
Scaling can be off Use the axis command to correct this
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2imagesc(xayaD)axis equal tight
No axis command axis equal tightaxis equal
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
21
Lecture 2 Slide 41
imagesc() (3 of 3)
Notice the orientation of the vertical axis using imagesc() MATLAB assumes it is drawing a matrix so the numbers increase going downward
imagesc(xayaD) h = imagesc(xayaD)h2 = get(hParent)set(h2YDirnormal)
Lecture 2 Slide 42
pcolor() (1 of 3)
pcolor() is like imagesc() but is better for displaying functions and smooth data because it has more options for this
xa = linspace(-1150)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)
axis equal tight
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
22
Lecture 2 Slide 43
pcolor() (2 of 3)
Here are the main options for shading
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2pcolor(xayaD)shading interpaxis equal tight
shading flatshading faceted shading interp
Lecture 2 Slide 44
pcolor() (3 of 3)
CAUTION When large arrays are visualized and faceted shading is selected (it is default) your image will appear completely black
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
23
Lecture 2 Slide 45
imagesc() vs pcolor()
A = [ 1 2 3 4 5 6 7 8 9]
Lecture 2 Slide 46
surf() (1 of 2)
surf() is like pcolor() but shows a 3D representation
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
24
Lecture 2 Slide 47
surf() (2 of 2)
The surf() command generates a 3D entity so it has all the properties and features of a 3D graph I recommend orbiting to find the best view as well as playing with the lighting
xa = linspace(-2250)ya = linspace(-1125)[YX] = meshgrid(yaxa)
D = X^2 + Y^2surf(xayaD)
axis equal tightshading interp
camlight lighting phongview(2545)
view(azel)
Lecture 2 Slide 48
Plotting Complex Functions
Suppose we wish to plot a complex function F(xy) MATLAB wonrsquot let us plot a complex function so we are forced to plot only the real part imaginary part magnitude phase etc
Re F x y Im F x y
F x y F x y
real(F) imag(F)
abs(F) angle(F)
Caution expect crazy results when your plotted function is a constant
5302017
25
Lecture 2 Slide 49
Colormaps
MATLAB gives you many options for colormaps
lsquojetrsquo is the default in 2014a and older versions of MATLAB
Use lsquograyrsquo for black and white printouts
colormap(lsquograyrsquo)
Lecture 2 Slide 50
Obtaining Smoother Color Shading
Colormaps define a range of colors but contain only discrete color levels
Smoother colors are obtained by using more color levels
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
29
Lecture 2 Slide 57
Annotation Arrows
annotation(arrowX[03205]Y[0604])
General Tips for Good Graphics
bull Ensure lines are thick enough to be easily seen but not too thick to be awkward
bull Ensure fonts are large enough to be easily read but not too large to be awkward
bull All axes should be properly labeled with unitsbull Figures should be made as small as possible so that everything is still easily observed and pleasing to the eye
bull Provide labels andor legends to identify everything in the figure
bull It is sometimes good practice to not include much formatting for graphics that will be updated many times during the execution of a code
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
33
Lecture 2 Slide 65
String Manipulation and Text Files
Lecture 2 66
Parsing Strings
A line of text can be parsed into separate words using sscanf()
S = Hello ClassT = sscanf(Ss s)
T =HelloClass
S = Hello ClassT = sscanf(Ss s)
T =Class
You can also extract numbers from a string using sscanf()
S = I am 25 years old and 6 feet tallN = sscanf(Ss s f s s s f s s)
N =256
skip string
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
34
Lecture 2 67
Checking for Specific Words in Strings (1 of 3)
You can perform an exact comparison between two strings using strcmp()
s1 = cats2 = dogc = strcmp(s1s2)
c =0
s1 = cats2 = Catc = strcmp(s1s2)
c =0
s1 = cats2 = catc = strcmp(s1s2)
c =1
Lecture 2 68
Checking for Specific Words in Strings (2 of 3)
You can do the same camparison but case insensitive using strcmpi()
s1 = cats2 = dogc = strcmpi(s1s2)
c =0
s1 = cats2 = Catc = strcmpi(s1s2)
c =1
s1 = cats2 = catc = strcmpi(s1s2)
c =1
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
35
Lecture 2 69
Checking for Specific Words in Strings (3 of 3)
You can find the occurrence of one string inside another using strfind()
s1 = University of Texas at El Pasos2 = Hawaiiind = strfind(s1s2)
ind =15
s1 = University of Texas at El Pasos2 = Texasind = strfind(s1s2)
ind =[]
Lecture 2 70
Converting Between Strings and Numbers
You can convert a string to a number using str2num()
S = 534N = str2num(S)
N =534
S = 274E-10N = str2num(S)
N =274E-10
Similarly you can convert numbers to strings using num2str()
N = 1234S = num2str(N)
S =1234
N = 123456789S = num2str(N)
S =12346
N = 123456789S = num2str(N16f)
S =1234568
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
36
Lecture 2 71
Opening and Closing Files
A file is opened in MATLAB as read‐only with the following command
OPEN ASCII STL FILEfid = fopen(lsquopyramidSTLrsquor) rsquorrsquo is read-only for safetyif fid==-1
error(Error opening file)end
A file is closed in MATLAB with the following command
CLOSE FILEfclose(fid)
Open and closing the file is always the first and last thing you doWARNING Always close open files
Use lsquowrsquo to write files
Lecture 2 72
Reading a Line from the Text File
A line of text is read from the text file using the following command
READ A LINE OF TEXTL = fgetl(fid)
You can read and display an entire text file with the following code
READ AND DISPLAY AN ENTIRE TEXT FILEwhile feof(fid)==0
Get Next Line from FileL = fgetl(fid)
Display the Line of Textdisp(L)
end
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns
Light lines are not visible against light backgrounds
line(xyColorwLineWidth3)
Dark lines are not visible against dark backgrounds
line(xyColorlsquokLineWidth3)
A solutionhellip
Plot the same line twice to give it an outline
line(xyColorwLineWidth6)line(xyColorkLineWidth3)
Lecture 2 Slide 90
Text Strings with Numbers
You can convert numbers to text strings using the num2str() function in MATLAB
It is possible to construct text strings with numbers within the string
gtgt num2str(32456)ans =32456
gtgt num2str(3245674f)ans =324560
gtgt [There are num2str(12) eggs in a dozen]ans =There are 12 eggs in a dozen
In FDTD it is sometimes helpful to report the iteration information in the title of a figure
title([FIELD AT STEP num2str(T) OF num2str(STEPS)])
5302017
46
Lecture 2 Slide 91
The parfor loop is perhaps the easiest way to parallelize your code
Before you can use the parfor loop you must initialize your processors This code must be placed at the start of your MATLAB program
INITIALIZE PARALLEL PROCESSINGif isempty(gcp)
pool = parpoolend
The parfor loop is used exactly like a regular for loop but the code inside the for loop is sent out to your different processors
parfor
PERFORM PARALLEL PROCESSINGparfor m = 1 M
hellipend
WARNING The code inside your loop must not depend on the results from any other iterations of the loop They must be completely independent
Lecture 2 Slide 92
Supplemental Software
5302017
47
Lecture 2 Slide 93
Software for Annotating and Manipulating Technical Drawings
For Editing Photographs and Images
The BestAdobe Photoshop
Open Source AlternativeGIMP
For Annotating Technical Drawings
The BestAdobe Illustrator
Open Source AlternativeInkscape
Lecture 2 Slide 94
3D Graphics
Open SourceBlender
5302017
37
Lecture 2 73
Writing a Line to the Text File
A line of text is written to the text file using fprintf()
WRITE A LINE OF TEXTfprintf(fidrsquosolid pyramidrnrsquo)
Write Facet Normal to FileN = [ 1234567 6876543 1592745 ]L = facet normal 86f 86f 86frnfprintf(fidLN)
Numbers can also be written to the file
This writes ldquosolid pyramidrdquo to the file followed by carriage line return
This writes ldquo facet normal 1234567e0 6876543e1 1592745e0rdquo to the file followed by carriage line return
Lecture 2 74
ANSI Formatting ‐‐ Summary
ESCAPE CHARACTERS
For most cases n is sufficient for a single line breakHowever if you are creating a file for use with MicrosoftNotepad specify a combination of rn to move to a new line
CONVERSION CHARACTERS
Value Type Conversion Details
Integer signed d or i Base 10 values
Integer unsigned u Base 10
Floating‐point number f Fixed‐point notation
e Exponential notation such as 3141593e+00
E Same as e but uppercase such as 3141593E+00
g The more compact of e or f with no trailing zeros
G The more compact of E or f with no trailing zeros
Characters c Single character
s String of characters
5302017
38
Lecture 2 75
ANSI Formatting ndash Conversion Characters
Lecture 2 76
ANSI Formatting ndash Flags
Action Flag Example
Left‐justify ndash -52f
Print sign character (+ or ndash) + +52f
Insert a space before the value 52f
Pad with zeros 0 052f
Modify selected numeric conversionsbull For o x or X print 0 0x or
0X prefixbull For f e or E print decimal
point even when precision is 0bull For g or G do not remove
trailing zeros or decimal point
50f
5302017
39
Lecture 2 Slide 77
Helpful Tidbits
Lecture 2 Slide 78
Initializing MATLAB
I like to initialize MATLAB this wayhellip
INITIALIZE MATLABclose all closes all figure windowsclc erases command windowclear all clears all variables from memory
5302017
40
Lecture 2 Slide 79
Initializing Arrays
A 10times10 array can be initialized to all zeros A = zeros(1010)
A 10times10 array can be initialized to all ones A = ones(1010)
A 10times10 array can be initialized to all random numbersA = rand(1010)
Numbers can also be put in manually Commas separate numbers along a row while semicolons separate columns