LECTURE_10_CS113_2010 - CS113
...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS113
 Introduction
to
Computing

 for
Engineers
 Formatting
Data,
Cell
Arrays
and
Case
 Structure
 Formatting
Data

 (#’s
and/or
strings)
 •  The
fprintf(
format,
data
)
function
 –  %d 
integer
 –  %5d
Integer,
minimum
width
=
5
 –  %f 
floating
point
format
 –  %4f

Floating
point,
minimum
width
=
4
 –  %6.3f 
Float,
min
width
=
6,
with
2
digits
past
decimal
 point.
 –  %e 
exponential
format
 –  \n 
new
line
character
 –  \t 
tab
character
 MATLAB
Basics:

 Displaying
Data
 –  fprintf( 'Result is %d', 3 ); Result is 3 –  fprintf( 'Area of a circle with radius %d is %f\n', 3, pi*3^2 ); Area of a circle with radius 3 is 28.274334 –  x = 5; –  fprintf( 'x = %3d\n', x ); x= 5 –  x = pi; –  fprintf( 'x = %0.2f\n', x ); x = 3.14 –  fprintf( 'x = %6.2f\n', x ); x= 3.14 –  fprintf( 'x = %d\ny = %d\n', 3, 13 ); x=3 y = 13 Opening
Files
 •  fid
=
fopen(
filename,
permission
)
 opens
the
file
filename
in
the
mode
specified
by
 permission
 –  fid
is
the
file
id
(a
positive
integer)
that
is
assigned
to
 the
file
by
MATLAB
 –  fid
is
used
for
all
reading,
writing
and
control
 operations
on
that
file
 –  file
id
1
is
the
standard
output
device
and
file
id
2
is
the
 standard
error
device
 –  fid
will
contain
‐1
if
the
file
could
not
be
opened
 Opening
Files
 •  Permission
can
be:
 –  ‘r ’:
open
file
for
reading
(default)
 –  ‘w’:
open
file,
or
create
a
new
file,
for
writing;
discard
 existing
contents,
if
any
 –  ‘a’:
open
file,
or
create
a
new
file,
for
writing;
append
 data
to
the
end
of
the
file
 –  ‘r+’:
open
file
for
reading
and
writing
 –  ‘w+’:
open
file,
or
create
a
new
file,
for
reading
and
 writing;
discard
existing
contents,
if
any
 –  ‘a+’:
open
file,
or
create
a
new
file,
for
reading
and
 writing;
append
data
to
the
end
of
the
file
 •  Add
‘t ’
to
the
permission
string
for
a
text
file
 Opening
Files
 •  Examples:
 –  fid
=
fopen(
‘example.dat ’,
‘r ’
)
 opens
a
binary
file
for
input
 –  fid
=
fopen(
‘example.dat ’,
‘wt ’
)
 opens
a
text
file
for
output
(if
example.dat
 already
exists,
it
will
be
deleted)
 –  fid
=
fopen(
‘example.dat ’,
‘at ’
)
 opens
a
text
file
for
output
(if
example.dat
 already
exists,
new
data
will
be
appended
to
 the
end)
 Closing
Files
 •  status
=
fclose(
fid
)
 closes
the
file
with
file
id
fid
 –  If
the
closing
operation
is
successful,
status
will
 be
0
 –  If
the
closing
operation
is
unsuccessful,
status
 will
be
‐1
 •  status
=
fclose(
‘all’
)
 closes
all
open
files
(except
for
standard
 output
and
standard
error)
 Writing
Formatted
Text
Data
 •  count
=
fprintf(fid,format,val1,val2,…)
 writes
formatted
text
data
in
a
user‐ specified
format
 –  fid:
file
id
(if
fid
is
missing,
data
is
written
to
the
 standard
output
device
(command
window)
 –  format:
same
as
what
we
have
been
using
 (combination
of
format
specifiers
that
start
 with
%)
 –  count:
number
of
characters
written
 Writing
Formatted
Text
Data
 •  Make
sure
there
is
a
one‐to‐one
correspondence
 between
format
specifiers
and
types
of
data
in
 variables
 •  Format
strings
are
scanned
from
left
to
right
 •  Program
goes
back
to
the
beginning
of
the
format
 string
if
there
are
still
values
to
write
(format
string
is
 recycled)
 •  If
you
want
to
print
the
actual
%
character,
you
can
 use
%%
in
the
format
string
 Formatted
Text
I/O
Examples
 % % Script file: writedata.m Purpose: Write out a simple data set. % Data to write out: xx = linspace(0,3*pi, 400); yvals = sin(xx); % Open the file for writing to file named “sinewave.dat”: fid = fopen('sinewave.dat', 'w'); % Print the data for ii = 1:length(xx) fprintf (fid, '%f\t%f \n', xx(ii), yvals(ii)); end % Close the file. status = fclose(fid); Formatted
Text
I/O
Examples
 % % Script file: table.m Purpose: To create a table of square roots, squares, and cubes. % Open the file. fid = fopen('table.dat', 'wt'); % Print the title of the table. fprintf(fid, ' Table of Square Roots, Squares, and Cubes\n\n'); % Print column headings fprintf(fid, ' Number Square Root fprintf(fid, ' ====== =========== Square ====== Cube\n'); ====\n'); % Generate the required data ii = 1:10; square_root = sqrt(ii); square = ii.^2; cube = ii.^3; % Print the data for ii = 1:10 fprintf (fid, ' %2d %11.4f %6d %8d\n', ... ii, square_root(ii), square(ii), cube(ii)); end % Close the file. status = fclose(fid); Reading
Formatted
Text
Data
 •  [array,count]
=
fscanf(fid,format,size)
 reads
formatted
text
data
in
a
user‐specified
 format
 –  fid:
file
id
 –  format:
same
as
format
in
fprintf
 –  size:
same
as
size
in
fread
 –  array:
array
that
receives
the
data
 –  count:
number
of
elements
read
 Reading
Formatted
Text
Data
 •  line
=
fgets(
fid
)
 reads
the
next
line
including
the
end‐of‐line
 characters
from
a
file
as
a
character
string
 –  line:
character
array
that
receives
the
data
 –  line
is
set
to
‐1
if
fgets
encounters
the
end
of
a
file
 Formatted
Text
I/O
Examples
 %Updates the name of a person %Get the old and new names old_name = input( 'Enter the old name: ', 's' ); new_name = input( 'Enter the new name: ', 's' ); %Open the input file fid1 = fopen( 'phones.txt', 'rt' ); %Open the output file fid2 = fopen( 'phones3.txt', 'wt' ); %Read lines one by one line = fgets( fid1 ); while ( line > 0 ), %Replace the old name with the new name line2 = strrep( line, old_name, new_name ); %Write to the new file fprintf( fid2, '%s', line2 ); %Read the next line line = fgets( fid1 ); end %Close the file status = fclose( 'all' );
 Why
does
this
not
work?
 •  >>A=‘blue’;
 •  >>B=‘red’;
 •  >>C=‘green’;
 •  >>
colors=[A;
B;
C];
 ???
Error
using
==>
vertcat
 All
rows
in
the
bracketed
expression
must
 have
the
same

 number
of
columns.
 Why
does
this
not
work?
 •  •  •  •  •  >>A=‘blue’;
 >>B=‘red’;
 >>C=‘green’;
 >>
colors=[A;
B;
C];
 >>
whos
 Name A B C Size 1x4 1x3 1x5 Bytes Class 8 char array 6 char array 10 char array How
do
we
solve
this
problem?
 I
want
a
list
of
words
and
I
want
to
save
them
as
a
single
 variable
(i.e.
colors,
names,
…)
 •  •  •  •  •  >>A=‘blue’;
 >>B=‘red’;
 >>C=‘green’;
 >>
colors=[A;
B;
C];
 >>
whos
 Name A B C Size 1x4 1x3 1x5 Bytes Class 8 char array 6 char array 10 char array
 SOLUTION:

CELL
ARRAYS
 •  >> A = 'blue'; •  >> B = 'red'; Curly
bracket
indicates
a
cell
array
 •  >> C = 'green'; •  >> colors = {A; B; C}; •  >> whos Name Size Bytes Class A 1x4 8 char array B 1x3 6 char array C 1x5 10 char array colors 3x1 204 cell array So
What
is
a
CellArray?
 •  
A
cell
array
is
a
collection
of
arrays
of
various
 sizes
and
types.
 •  >> A = {'string array', [1:0.1:100],... ones(100,100)} •  >> A{1}= 'string array' •  >> A{2}= [1:0.1:100]; •  >> A{3}= ones(100,100); The
textread
Function
 •  It
is
designed
to
read
ASCII
files
that
are
 formatted
into
columns
of
data
 •  Each
column
can
be
of
a
different
type
 •  It
is
useful
for
importing
tables
of
data
printed
 out
by
other
applications
 The
textread
Function
 •  [a,b,c,…]
=
textread(filename,format,n)
 –  filename:
a
string
that
is
the
name
of
the
file
to
be
 read
 –  format:
a
string
containing
the
format
primitives
 ( just
like
in
fprintf)
 –  n:
number
of
lines
to
read
(if
not
specified,
the
file
 is
read
until
the
end)
 The
textread
Function
 •  Example:
Assume
that
you
have
a
file
called
 phones.txt
 
 Varol Akman Prof 1538 Selim Aksoy AsstProf 3405 Erol Arkun Prof 2249 Cevdet Aykanat Prof 1625 Mehmet Baray Prof 1208 Cengiz Çelik Instructor 2613 Ilyas Çiçekli AsstProf 1589 David Davenport AsstProf 1248
 ...
 The
textread
Function
 •  [fname,lname,rank,phone]
=
 textread(
'phones.txt',
'%s
%s
%s
%d'
)
 –  fname
=

 



'Varol‘
 



'Selim‘
 



'Erol‘
 



'Cevdet‘
 



'Mehmet‘
 



'Cengiz‘
 



...
 cell array –  phone
=
 







1537
 







3405
 







2249
 







1625
 







1208
 







2613
 







...
 double array The
textread
Function
 •  The
textread
function
skips
the
columns
 that
have
an
asterisk
(*)
in
the
format
 descriptor
 –  [fname,
phone]
=
 textread(
'phones.txt',
'%s
%*s
%*s
%d'
)
 •  The
load
command
(with
ASCII
option)
 assumes
all
of
the
data
is
of
a
single
type
 but
textread
is
more
flexible
 MATLAB
Basics:
Data
Files
 Saving
workspace
variables
 •  save
filename
var1
var2
…
 –  save homework.mat x y –  save –ascii x.dat x 

binary
 

ascii
 •  load
filename
 –  load filename.mat 
 –  load –ascii x.dat 
 

binary
 

ascii
 The
switch
Statement
 THE
“switch”
STATEMENT:
 •  Provides
a
convenient
way
to
execute
 conditional
code
when
there
are
many
cases
 to
choose
from.
 •  This
construct
can
replace
series
of
if‐else‐end
 statements
 LOGICAL
PROGRAMMING
CONSTRUCTS
 SYNTAX:
 switch expression (scalar or string) case value1 statement group 1 case value2 statement group 2 … otherwise statement group n end EXAMPLE
for
“switch”
 •  Suppose
you
are
given
a
variable
angle
in
 degrees
to
represent
the
following
directions:
 Northeast,
Southeast,
Southwest,
and
 Northwest.


 •  Use
the
switch
statement
to
display
the
 desired
direction
given
the
angle.
 SOLUTION
 switch angle Decision variable name case 45 disp('Northeast') Value to test case 135 disp('Southeast') case 225 disp('Southwest') case 315 disp('Northwest') Default case otherwise disp('Direction Unknown') end EXAMPLE
#2
for
“switch”
 •  You
input
a
numerical
value
of
a
quantity
in
 one
set
of
units
(e.g.,
centimeters)
and
you
 desire
an
output
in
another
set
of
units
(e.g.,
 inches,
feet,
or
meters,
etc…).


 •  Write
a
program
using
the
switch‐case
 construction
that
transforms
a
length
in
 centimeters,
inches,
feet,
meters,
etc…
to
 length
in
centimeters
 SOLUTION
 switch units case {'inch','in'} % ‘units’ contains type of y = x*2.54; % input, output is in cm case {'feet','ft'} y = x*2.54*12; case {'meter','m'} y = x*100; case {'centimeter','cm'} y = x; case {'millimeter','mm'} y = x/10; otherwise disp(['Unknown Units: ' units]) y = NaN; end ...
View Full Document

This note was uploaded on 02/29/2012 for the course CSC 113 taught by Professor Phillipregali during the Fall '10 term at Catholic University of America.

Ask a homework question - tutors are online