APPLICATIONS OF
MATLAB IN ENGINEERING
Yan-Fu Kuo Fall 2015
Dept. of Bio-industrial Mechatronics Engineering
National Taiwan University
Today:
• Variables: string, structure, cell
• Data access
Applications of MATLAB in Engineering Y.-F. Kuo 2
MATLAB Data (Variables) Types
Applications of MATLAB in Engineering Y.-F. Kuo 3
Variable (Data) Type Conversion
double() Convert to double precision
single() Convert to single precision
int8() Convert to 8-bit signed integer
int16() Convert to 16-bit signed integer
int32() Convert to 32-bit signed integer
int64() Convert to 64-bit signed integer
uint8() Convert to 8-bit unsigned integer
uint16() Convert to 16-bit unsigned integer
uint32() Convert to 32-bit unsigned integer
uint64() Convert to 64-bit unsigned integer
Applications of MATLAB in Engineering Y.-F. Kuo 4
Character (char)
• A character is represented in ASCII using a
numeric code between 0 to 255
• Create a character or a string by putting them into
a pair of apostrophe:
s1 = 'h' s2 = 'H'
whos whos
uint16(s1) uint16(s2)
Applications of MATLAB in Engineering Y.-F. Kuo 5
Applications of MATLAB in Engineering Y.-F. Kuo 6
String
• An array collects characters:
s1 = 'Example';
s2 = 'String';
• String concatenation:
s3 = [s1 s2];
s4 = [s1; s2];
Applications of MATLAB in Engineering Y.-F. Kuo 7
Logical Operations and Assignments
• Many numerical and logical operators can be
applied to strings
str = 'aardvark';
'a' == str
• Try this:
str(str == 'a') = 'Z'
• What if we want to compare the entire string with
another?
Applications of MATLAB in Engineering Y.-F. Kuo 8
Exercise
• Write a script that inverts any given string
s1='I like the letter E'
s2='E rettel eht ekil I'
Applications of MATLAB in Engineering Y.-F. Kuo 9
Structure
• A method of storing heterogeneous data
• Structures contain arrays called fields
• Student assignment grades:
student.name = 'John Doe';
student.id = 'jdo2@sfu.ca';
student.number = 301073268;
student.grade = [100, 75, 73; ...
95, 91, 85.5; ...
100, 98, 72];
student
Applications of MATLAB in Engineering Y.-F. Kuo 10
Adding Information to A Structure
student(2).name = 'Ann Lane';
student(2).id = 'aln4@sfu.ca';
student(2).number = 301078853;
student(2).grade = [95 100 90; 95 82 97; 100 85 100];
• Retrieve the 3rd grade for Ann Lane
Applications of MATLAB in Engineering Y.-F. Kuo 11
Structure Functions
cell2struct Convert cell array to structure array
fieldnames Field names of structure, or public fields of object
getfield Field of structure array
isfield Determine whether input is structure array field
isstruct Determine whether input is structure array
orderfields Order fields of structure array
rmfield Remove fields from structure
setfield Assign values to structure array field
struct Create structure array
struct2cell Convert structure to cell array
structfun Apply function to each field of scalar structure
• Try: fieldnames(student)
rmfield(student,'id')
Applications of MATLAB in Engineering Y.-F. Kuo 12
Nesting Structures
A = struct('data', [3 4 7; 8 0 1], 'nest', ...
struct('testnum', 'Test 1', ...
'xdata', [4 2 8],'ydata', [7 1 6]));
A(2).data = [9 3 2; 7 6 5];
A(2).nest.testnum = 'Test 2';
A(2).nest.xdata = [3 4 2];
A(2).nest.ydata = [5 0 9];
A.nest
Applications of MATLAB in Engineering Y.-F. Kuo 13
Cell Array
• Another method of storing heterogeneous data
• Similar to matrix but each entry contains different
type of data
• Declared using { } A(1,1)={[1 4 3; 0 5 8; 7 2 9]};
A(1,2)={'Anne Smith'};
A(2,1)={3+7i};
1 4 3 A(2,2)={-pi:pi:pi};
0 5 8 'Anne Smith' A
7 2 9
A{1,1}=[1 4 3; 0 5 8; 7 2 9];
A{1,2}='Anne Smith';
3+7i −𝜋 0 𝜋 A{2,1}=3+7i;
A{2,2}=-pi:pi:pi;
A
Applications of MATLAB in Engineering Y.-F. Kuo 14
How Does MATLAB Do It?
• Each entry in a
cell array holds a
pointer to a data
structure
• Different cells of
the same cell
array can point to
different types of
data structures
Applications of MATLAB in Engineering Y.-F. Kuo 15
Exercise
• Create a cell array B that has the following
structure
[5+j*6 4+j*5]
'This is the first cell'
(1x2 complex
(String)
number array)
1 2 3
4 5 6 {'Tim', 'Chris'}
7 8 9 (1X2 string array)
(3x3 integer array)
Applications of MATLAB in Engineering Y.-F. Kuo 16
Accessing Cell Array
• Curly braces, { }, are used to access the “content”
of cell arrays
• What are the differences between C and D?
C = A{1,1}
D = A(1,1)
• How do I get this number? 1 4 3
0 5 8 'Anne Smith'
7 2 9
3+7i −𝜋 0 𝜋
Applications of MATLAB in Engineering Y.-F. Kuo 17
Cell Array Functions
cell Create cell array
cell2mat Convert cell array to numeric array
cell2struct Convert cell array to structure array
celldisp Cell array contents
cellfun Apply function to each cell in cell array
cellplot Graphically display structure of cell array
cellstr Create cell array of strings from character array
iscell Determine whether input is cell array
mat2cell Convert array to cell array with different sized cells
num2cell Convert array to cell array with consistently sized cells
struct2cell Convert structure to cell array
Applications of MATLAB in Engineering Y.-F. Kuo 18
num2cell() and mat2cell()
• Transform a matrix into a cell variable
a = magic(3)
b = num2cell(a)
c = mat2cell(a, [1 1 1], 3)
num2cell mat2cell
Applications of MATLAB in Engineering Y.-F. Kuo 19
Multidimensional Array
A{1,1,1} = [1 2;4 5];
A{1,2,1} = 'Name';
A{2,1,1} = 2-4i;
A{2,1,1} = 7;
A{1,1,2} = 'Name2';
A{1,2,2} = 3;
A{2,1,2} = 0:1:3;
A{2,2,2} = [4 5]';
Applications of MATLAB in Engineering Y.-F. Kuo 20
cat()
• Array concatenation
A=[1 2;3 4]; B=[5 6;7 8];
C=cat(1,A,B) C=cat(2,A,B) C=cat(3,A,B)
Applications of MATLAB in Engineering Y.-F. Kuo 21
Multidimensional Array
A{1,1} = [1 2;4 5];
A{1,2} = 'Name';
A{2,1} = 2-4i;
A{2,2} = 7;
B{1,1} = 'Name2';
B{1,2} = 3;
B{2,1} = 0:1:3;
B{2,2} = [4 5]';
C = cat(3, A, B)
Applications of MATLAB in Engineering Y.-F. Kuo 22
reshape()
• Returns a new array with assigned rows and columns
A = {'James Bond', [1 2;3 4;5 6]; pi, magic(5)}
C = reshape(A,1,4)
• Create a matrix B from the matrix A below using reshape:
A = [1:3; 4:6];
1 5
1 2 3
𝐴= 𝐵= 4 3
4 5 6
2 6
Applications of MATLAB in Engineering Y.-F. Kuo 23
Checking Variable And Variable Status
isinteger Determine if input is integer array
islogical Determine if input is logical array
isnan Detect an element that isnot a number (NaN)
isnumeric Determine if input is numeric array
isprime Detect prime elements of array
isreal Determine if all array elements are real numbers
iscell Determine if input is cell array
ischar Determine if input is character array
isempty Determine if input is empty array
isequal Determine if arrays are numerically equal
isfloat Determine if input is floating-point array
isglobal Determine if input is global variable
ishandle Detect valid graphics object handles
isinf Detect infinite elements of array
Applications of MATLAB in Engineering Y.-F. Kuo 24
File Access
File Work
System Space
• Supported file formats:
Import Export
File Content Extension Description
Function Function
MATLAB MAT Saved MATLAB workspace load save
formatted data
Text Space delimited numbers load save
Spreadsheet XLS, XLSX xlsread xlswrite
Applications of MATLAB in Engineering Y.-F. Kuo 25
save() and load()
• Save (all) workspace data to a file:
clear; a = magic(4);
save mydata1.mat
save mydata2.mat -ascii
• Load data stored in a file:
load('mydata1.mat')
load('mydata2.mat','-ascii')
• How does one save a specific variable?
Applications of MATLAB in Engineering Y.-F. Kuo 26
Excel File Reading: xlsread()
• Read from Excel spreadsheet
Score = xlsread('04Score.xlsx')
Score = xlsread('04Score.xlsx', 'B2:D4')
Applications of MATLAB in Engineering Y.-F. Kuo 27
Excel File Writing: xlswrite()
• Calculate the means and write into Excel
spreadsheet
M = mean(Score')';
xlswrite('04Score.xlsx', M, 1, 'E2:E4');
xlswrite('04Score.xlsx', {'Mean'}, 1, 'E1');
• Calculate the standard deviations and write them
into column F
Applications of MATLAB in Engineering Y.-F. Kuo 28
Getting Text in Excel Spreadsheet
• Getting both the text and numbers
[Score Header] = xlsread('04Score.xlsx')
• How do we write both the text and number into an
Excel file?
Applications of MATLAB in Engineering Y.-F. Kuo 29
Low-level File Input/Output
• Read and write file at the
byte or character level
• A file has an ID fid
• Location in the file is
specified by a pointer that
can be moved around
Pointer
John 1995 12 5 12.3 3.24
fid Tom 1995 12 7 2.3 2.0
Jean 1996 3 2 10.2 0
Applications of MATLAB in Engineering Y.-F. Kuo 30
Low-level File I/O Functions
Function Description
fopen Open file, or obtain information about open files
fclose Close one or all open files
fscanf Read data from text file
fprintf Write data to text file
feof Test for end-of-file
• Open and close a file:
fid = fopen('[filename]', '[permission]');
'r' 'r+' 'w'
status = fclose(fid); 'w+' 'a' 'a+'
Applications of MATLAB in Engineering Y.-F. Kuo 31
Writing Sine Values into A File
x y
1
0.000 0.0000
0.8 0.314 0.3090
0.628 0.5878
0.6 0.942 0.8090
1.257 0.9511
0.4 1.571 1.0000
1.885 0.9511
0.2 2.199 0.8090
2.513 0.5878
0 2.827 0.3090
0 1 2 3
3.142 0.0000
x = 0:pi/10:pi; y = sin(x); fid = fopen('sinx.txt','w');
for i=1:11
fprintf(fid,'%5.3f %8.4f\n', x(i), y(i));
end
fclose(fid); type sinx.txt
Applications of MATLAB in Engineering Y.-F. Kuo 32
Read and Write through Formatted I/O
• Read: A = fscanf(fid, format, size);
Data Format Data to Amount of
read specifier write data to read
• Write: fprintf(fid, format, x, y,...);
• Format specifier: %-12.5e width and precision
Specifier Description
%c Single character %o Octal notation (unsigned)
%d Decimal notation (signed) %s String of characters
%e Exponential notation %u Decimal notation (unsigned)
%f Fixed-point notation %x Hexadecimal notation
%g The more compact of %e or %f
Applications of MATLAB in Engineering Y.-F. Kuo 33
Reading from Files
• Check if it is the end of file: feof(fid)
• 04asciiData.txt: John 1995 12 5 12.3 3.24
Tom 1995 12 7 2.3 2.0
Jean 1996 3 2 10.2 0
fid = fopen('04asciiData.txt','r'); i = 1;
while ~feof(fid)
name(i,:) = fscanf(fid,'%5c',1);
year(i) = fscanf(fid,'%d',1);
no1(i) = fscanf(fid,'%d',1);
no2(i) = fscanf(fid,'%d',1);
no3(i) = fscanf(fid,'%g',1);
no4(i) = fscanf(fid,'%g\n');
i=i+1;
end
fclose(fid);
Applications of MATLAB in Engineering Y.-F. Kuo 34
End of Class