© Bar-Ilan University Computer Center
MATLAB concepts Course
Data types MATLAB concepts
• Numeric: double (computations), single, signed and unsigned integer types • Logic (numeric) • Sparse (numeric) • Characters • Structures • Cell arrays • MATLAB and user classes (structure) • Java class • function handles
Session 2 I/O and Data types
1
2
Strings
Characters
• String = an array of characters. • Creation in MATLAB:
• Character = a printable/readable sign, represented by a two-byte ascii code. • Creation in MATLAB:
'' will create a 1D string. Example: A = 'this is a string' char(N) where 0 < N < 65535 is the ascii code array
'' Examples: 'r' or '.' or ' ' char(N) where 0 < N < 65535 is the ascii code
• Usage of strings: Textual data Headers, title and annotation in graphics Names of files, variables and structure fields
• double(character) get ascii code of character 3
String manipulation
4
String conversion
• Like any array. • Convert a number to a string: num2str • Convert an integer to a string: int2str • Convert a string to a number: str2num
Concatenation of strings Selection of characters in a string deletion of characters in a string
• blanks(n) Create a row vector of n blanks • strtrim(str) Remove leading and trailing white space from character string str. 5
April 10
If the string does not represent a number, returns an empty array NaN is recognized
6
Session 2 page 1
© Bar-Ilan University Computer Center
MATLAB concepts Course
Importing data into MATLAB
User-choice: files
• The load command: load filename • Load binary: filename without extension, assumes .mat Example: load myvars will look for a file myvars.mat and will load all variables in it. • Load ascii: filename with any extension except .mat will load one matrix. Example: load onetest.dat will create a variable named onetest. Functional form: var = load(‘file name’)
• uigetfile(FilterSpec) display a dialog box that lists files in the current directory according to FilterSpec return the user’s choice as a string.
• uigetdir Display a dialog box that lists directories in the current directory return the user’s choice as a string.
7
• Read excel files: A = xlsread('file-name') • Other formats: help fileformats
8
Keyboard input
Saving data to disk
• user_entry = input(prompt)
• The save command: save filename vars • Save variables in binary: assumes .mat. save filename var1 var2 var3 … save filename will save all variables. • Save numerical matrices in readable format: save name.ext var1 var2 … -ascii will print var1, var2 etc. into a file, each row in a new line. • Functional form: save('filename','var1','var2','-ascii') Demo: Strings
display the string variable prompt as a prompt on the screen Wait for input from the keyboard Interpret numeric characters as numbers and character input as variable names return the value entered in user_entry
• input_string = input(prompt,’s’) return the entered string as-is
9
The plot command • • • • • • •
Colors and line-styles
plot(x,y) → default: solid line, no markers plot(y) → default: x = 1,2, … , length(y) Default color Automatic scaling Default tick marks No titles Multiple curves: If y is a matrix or x,y are matrices, each column produces a curve. 11
April 10
10
Curve style: plot(x,y,'style-chars')
Colors b blue g green r red c cyan m magenta y yellow k black
Line Styles - solid -- dashed : dotted -. dot-dashed
12
Session 2 page 2
© Bar-Ilan University Computer Center
MATLAB concepts Course
Texts
Markers . o x +
point circle x +
* s d
star square diamond
v ^ < > p h
• • • • • •
Plot title: title('text') x-axis title: xlabel('text') y-axis title: ylabel('text') Legend: legend('text1','text2',…) Remove legend: legend off text(x,y, 'str') : Write str at data coordinates (x,y) with default properties • Adding a text does not change axis scaling.
triangle (down) triangle (up) triangle (left) triangle (right) pentagram hexagram
13
14
Printing and saving plots
Adding and deleting curves
• Send a plot to default printer: print • Save into a file: print -device fname • Common devices: BMP 24-bit -dbmp EPS black and white -deps JPEG 24-bit -djpeg PDF Color PDF file -dpdf • Example: print -djpeg exmpl will create a file named exmpl.jpg Demo: Graphics • Functional form: print('-device','fname') Questions 1-3
• Default: every plot command overrides previous plots. • hold on: switch to adding-plots mode • hold off: switch to override mode • clf: clear figure • Default: adding curves automatically changes scaling, unless there was a userdefined scaling. 15
Cell-arrays
16
Cell-array: example
• Cell array = an array whose elements are arrays themselves. • A cell can be of any type, including a cell array
C: cell 1x3 C{1}
C{2} Cell 4x1
C{3} Cell 3x2
1X10
9x4
9x2
1X12
2x2
3x2
1X8
5x7
2x7
1X6 17
April 10
18
Session 2 page 3
© Bar-Ilan University Computer Center
MATLAB concepts Course
Working with cell-arrays Cell-arrays in graphic annotation
• Creation: use listing with curly brackets {} • Reference to elements in the array: C(2) • Reference to cell contents:
• Multiple-line texts: – A cell-array of strings, each cell is a text line. – Applies to text, title, xlabel and ylabel.
one level: C{2} more levels: C{3}{3,2} one level, element is an array: C{1}(5)
• Cell-array form of legend: legend({cell-array of strings})
• Concatenation: [cell1 cell2 cell3 … ] • Assignment: cell_array{index}=val 19
20
User-choice: menu
Structures
• The menu command: k = menu(mtitle,opt1,opt2,...,optn) • Display the menu whose title is a string variable mtitle and whose choices are string variables opt1, opt2, and so on. • Cell-array form: k = menu(mtitle,{cell-array of strings}) • Return the index k of the selected menu item.
Structure: a collection of different kinds of data, organized by named fields. Variable name field1 field2
A field can be of any type, including a structure or a cell-array.
field3
Demo: Cell-arrays Questions 4-5
field4
21
Structures - example
22
Structures – creation and reference
Spectra: ST
•
Clean: ST Raw: numeric 2D
Filename: string Inputs: cell 1D
•
Lipid: ST
Field is an array: spectra.species(5,:) Field is a cell-array: spectra.inputs{3} Field is a structure: spectra.clean.raw
Creation
Raw: numeric 2D
by assignment var.field=value
Filename: string
Using a command struct('field1',VAL1,'field2',VAL2,...)
Inputs: cell 1D 23
April 10
Reference: varname.fieldname
24
Session 2 page 4
© Bar-Ilan University Computer Center
MATLAB concepts Course
Importdata: generalized input
Structure arrays • Structure array = array of structures with the same field names. • Reference varname(index).fieldname
• If some of the fields are missing from some of the array elements, MATLAB automatically assigns an empty matrix.
25
• Creates a structure, fields depend on the type of and data in the file. • Usage: S = importdata(filename) • Excel and text files data: the largest numeric matrix textdata: all texts colheaders: column headers
• mat files: variables are fields • Others (.wav, .jpg) Demo: structures Question 6
26
dir command • Returns info on all files according to FilterSpec • Usage: Flist = dir(FilterSpec) • Flist is a structure array, one structure for each file, with the following fields: name date bytes isdir datenum 27
April 10
Session 2 page 5