Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Ch01 - Introduction To MATLAB+Ch02 - MATLAB Basics (Part 1)

Uploaded by

dgdzheng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Ch01 - Introduction To MATLAB+Ch02 - MATLAB Basics (Part 1)

Uploaded by

dgdzheng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

MATLAB Programming for Engineers

Ming Jiang

www.wcomms.com
课程介绍 (1/2)

教学目的及要求
• 主要介绍MATLAB编程语言的基本功能、特点及如何使用其来解决工程领域的
典型技术问题,如科学计算、算法仿真等
• 通过本课程的学习,学生应掌握如何编写实用、高效的MATLAB程序,了解使
用MATLAB解决工程与技术问题的方法,学习如何使用MATLAB的帮助系统查
询所需的目标函数等,从而提高逻辑思维与解决问题的能力

教学特色
• 在完成教材基本内容讲解的基础上,适当将电子专业基础理论课(如通信原理
等)的部分知识点以例子或习题的形式融入教学,让学生结合MATLAB编程进
行学习或复习
• 学生可同时在专业基础知识和MATLAB编程两个方面加深理解
• 通过布置适量的课后作业并适时安排一些简单的研究类课题,供学生进行理论
验证或实验研究,培养学生的创新思维与实际动手解决问题的能力

Ming Jiang www.wcomms.com 2


课程介绍 (2/2)

参考资料
• Stephen J. Chapman,《MATLAB编程》(第四版影印版),
科学出版社, 2011年4月, ISBN: 9787030305428
• Stephen J. Chapman, "MATLAB Programming for
Engineers" (4th Edition), Thomson Learning, Nov.
2007, ISBN: 9780495244493
• Amos Gilat, MATLAB: An Introduction with
Applications (4th Edition), John Wiley & Sons,2010年1
月,ISBN: 9780470767856
• 张威, MATLAB基础与编程入门 (第二版), 西安电子科技大学
出版社, 2008年1月, ISBN: 7560613306
• Brian R. Hunt, Ronald L. Lipsman, Jonathan M.
Rosenberg, "A Guide to MATLAB: for Beginners and
Experienced Users" (2nd Edition), Cambridge University
Press, Jun. 2006, ISBN: 9780521615655

Ming Jiang www.wcomms.com 3


Chapter 1: Introduction to MATLAB

Ming Jiang

www.wcomms.com
MATLAB Programming for Engineers
Chapter 1: Introduction to MATLAB

• What is MATLAB
• MATLAB runtime environment

Ming Jiang
The First Look

What is MATLAB ?
• MATrix LABoratory
• A computer program for engineering and scientific calculations
• Before: designed to perform matrix mathematics
• Now: a flexible computing system for solving any technical problem
What can MATLAB offer?
• MATLAB provides an incredibly rich variety of functions
• 1000+ basic functions -> much richer than other technical
programming languages
• Additional toolkits for different technical areas
What to learn?
• NOT possible to learn ALL MATLAB functions in this course
• Instead, students should:
• Understand how to write/debug/optimize MATLAB programs
• Get familiar with a subset of the most important functions
• Know how to search for the right function needed

Ming Jiang www.wcomms.com 6


Fortran and Scientific Computing

• Engineering / scientific applications involve lots of "number crunching"


• Many technical problems cannot be solved by theoretical derivations
• The need of numerical computing and simulations

• For many years, Fortran ("Formula Translating System") is used


• The first "high-level" programming language
• Especially designed for numerical computing

Example: Fortran code to solve a*x2 + b*x + c = 0

C Solve a quadratic equation (this is a comment).


DESC = B*B - 4*A*C
IF ( DESC .LT. 0.0 ) GOTO 10
DESC = SQRT(DESC)
X1 = (-B + DESC)/(2.0*A)
X2 = (-B - DESC)/(2.0*A)
WRITE(6,*) "SOLUTIONS ARE ",X1," AND ", X2
RETURN
10 WRITE(6,*) "EQUATION HAS COMPLEX ROOTS"
RETURN

Ming Jiang www.wcomms.com 7


Solving a Linear System in Fortran

Example: Fortran code to solve a linear system b = A*x, solve for x


(no check for degeneracy or zeros)

C Solve B = A*X for X. C... Backwards substitution


C N is dimension of vectors and matrix X(N) = X(N)/A(N,N)
C Does not use row interchange, scaling. DO 21 I=N-1,1,-1
SUBROUTINE LINSYS(N, A, X, B, TMP) TMP = X(I)
INTEGER N DO 20 J=I+1,N
DOUBLE PRECISION A(N,N), X(N), B(N) 20 TMP = TMP - A(I,J)*X(J)
DOUBLE PRECISION TMP(N), RATIO X(I) = TMP/A(I,I)
C... Forward elimination 21 CONTINUE
DO 13 J=1,N-1 RETURN
DO 12 I=J+1,N END
RATIO = -A(I,J)/A(J,J)
A(I,*) = A(I,*) +RATIO*ROW(J,*)
DO 11 K=J+1,N
11 A(I,K) = A(I,K) + RATIO*A(J,K) This is just a small example.
A(I,J) = 0.0
A full program may be
X(I) = X(I) + RATIO*X(J)
12 CONTINUE thousands of lines long!
11 CONTINUE
To be continued...

Ming Jiang www.wcomms.com 8


Introduction of Numerical Libraries

• BLAS (Basic Linear Algebra Subroutines)


• For operations on vectors, e.g. vectors addition, dot product,
norm, etc.
• LINPACK
• Linear algebra subroutines for vector-matrix operations,
solving linear systems, factoring a matrix, inverting a matrix
• LINPACK has now been replaced by LAPACK
• EISPACK
• Compute eigenvalues and eigenvectors of matrices

Example: solve A*x = b C.... factor the A matrix


CALL SGEFA(A, N, N, IPVT, INFO)
using LINPACK C.... copy B vector into X vector
CALL SCOPY(N, B, 1, X, 1)
C.... solve the system of equations
CALL SGESL(A, N, N, IPVT, X, 0)

Ming Jiang www.wcomms.com 9


Still Not Easy Enough! So…

• Cleve Moler, CS Professor at the University of New


Mexico, and co-author of LINPACK, thought this is
still too much work
• Write Fortran, compile, debug, compile, run...
• In order to give students easy access to LINPACK,
Prof. Moler started developing MATLAB in the late
1970s
• Interactive
• Easy input, easy output
• Operations on a whole vector or matrix at once

Example:
x = A \ b
solve b = A*x in MATLAB
YES! Just as simple
as you see it!
Ming Jiang www.wcomms.com 10
Immediate Popularity!

• MATLAB quickly became quite popular and used for


both teaching and research - and it was also free
• An engineer, Jack Little, saw MATLAB during a
lecture by Prof. Moler at Stanford University in 1983
• He saw the commercial potential and (with Prof.
Moler's permission)
• Rewrote MATLAB in C
BSc. MIT • Added "M-files" (stored programs)
MEng. Stanford
• Added many new features and libraries
• Founded MathWorks® to commercially market it

• 6,000 staff in 34 global offices


• 6,500 academic customers
• Installations at over 100,000 organizations in
180 countries
• Revenue=$1.25b in 2023 (>80亿元)
• Profitable every year since its founding
Ming Jiang www.wcomms.com 11
MATLAB Today

• More than one million of users


• 1500 MATLAB based books in 28 languages
• A standard tool in both professional and academic use

• "Toolboxes" provide functions


for many applications: Typical Applications
• Communication systems • Math and computation
• Control systems • Algorithm development
• Identification • Modelling, simulation, and
• Neural networks prototyping
• Bio-informatics • Data analysis, exploration,
• Statistics and time-series and visualization
analysis • Scientific and engineering
• Support symbolic computation graphics
• Simulink: GUI-based simulation • Application development,
tool including Graphical User
Interface (GUI) building
Ming Jiang www.wcomms.com 12
Example: Simulations

Ming Jiang www.wcomms.com 13


MATLAB Programming for Engineers
Chapter 1: Introduction to MATLAB

• What is MATLAB
• MATLAB runtime environment

Ming Jiang
Installation Example: MATLAB 2019b (1/3)
MATLAB is FREE if you are a SYSUer!
https://software.sysu.edu.cn/matlab_dl

Ming Jiang www.wcomms.com 15


Installation Example: MATLAB 2019b (2/3)

Ming Jiang www.wcomms.com 16


Installation Example: MATLAB 2019b (3/3)

Do a full installation (30GB free space + 35 minutes needed),


or at least select the following to install
• MATLAB
• Communications Toolbox
• Computer Vision Toolbox
• Curve Fitting Toolbox
• DSP System Toolbox
• Image Processing Toolbox
• MATLAB Compiler
• Signal Processing Toolbox
• Symbolic Math Toolbox

Ming Jiang www.wcomms.com 17


Desktop Environment Example: MATLAB 2019b
Current Directory: Browser shows a View or change the Launch the
list of the files in the current directory current directory here Help Browser

Command History
Window: displays
previous
commands

Workspace
Browser: shows
variables defined in
MATLAB Command Window:
workspace
Type your MATLAB commands here

Ming Jiang www.wcomms.com 18


The Command Window

Example: Use of Ellipsis


• Allow users to enter
commands at/under x1=1+1/2+1/3+1/4 ...
the command prompt +1/5+1/6
• MATLAB calculates the
answer once the Enter
key is pressed This is a
Space!
• Ellipsis (...) is used if a
statement is too long

Ming Jiang www.wcomms.com 19


The Workspace Windows

• Shows computer memory


occupied by variables and
arrays used by MATLAB

• The whos command: List


variables and arrays in the
current workspace

Ming Jiang www.wcomms.com 20


The Edit/Debug and Figure Windows

• An Edit/Debug window is used to create a new .m file or to


modify an existing one
• A Figure Window is used to display MATLAB graphics

Click here to create a Execute the


new document M-file

Click here to open an


existing document

Ming Jiang www.wcomms.com 21


Important Commands
• clc: to clear the contents of the Command Window
• clf: to clear the contents of the current Figure Window
• clear: to clear the variables in the workspace
• ^c (ctrl+c): to abort current command
• !: to execute commands of computer's operating system -> Example: !explorer.exe
• diary: to copy all inputs and outputs displayed in the Command Window into a
diary file
• diary off: to suspend inputs into the diary file
• diary on : to resume inputs again
• demo: to run MATLAB's built-in demonstrations

Ming Jiang www.wcomms.com 22


Searching and Locating Files (1/3)

MATLAB searches files in this order:


• It looks for the name as a variable
• If it is, MATLAB displays the current contents of the variable
• It checks to see if the name is a built-in function or command
• If it is, MATLAB executes that function or command
• It checks to see if the name is an M-file in the current directory
• If it is, MATLAB executes that M-file
• It checks to see if the name is an M-file in any directory in the
search path
• If it is, MATLAB executes that M-file

Ming Jiang www.wcomms.com 23


Searching and Locating Files (2/3)

Add all the paths that your M-


files are located

Click here to
add the search
paths in your
OS

Ming Jiang www.wcomms.com 24


Searching and Locating Files (3/3)

• Warning:
• Never use a variable with the same Example:
name as a MATLAB function or sin=5; sin(1)=?
command
• Never create an m-file with the same
name as a MATLAB function or
command Not
• Otherwise, that MATLAB function or intended
command will become inaccessible! result!
• Use the which command to find out the
version of the file, and where it is located
-> avoid misuse of name

Ming Jiang www.wcomms.com 25


Getting Help (1/3)

Three ways to get Help in MATLAB

• Click the toolbar icon to launch the Help Browser


• Allow full access to the entire Matlab documentation set

Ming Jiang www.wcomms.com 26


Getting Help (2/3)

Three ways to get Help in MATLAB

• Type help string in the Command Window


• You must know the name of the function to get help about it

No function is called "ar"!

Ming Jiang www.wcomms.com 27


Getting Help (3/3)

Three ways to get Help in MATLAB

• Type lookfor string in the Command Window


• Search for a given string in the first comment line of
every MATLAB function, and display all matched results

Only three functions are


found to contain "acos"

Many files containing "ar" in


their first comment line

Ming Jiang www.wcomms.com 28


Chapter 2: MATLAB Basics
(Part 1)

Ming Jiang

www.wcomms.com
MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 1)

• Variables and Arrays


• Initializing Variables
• Multi-dimensional Arrays and Subarrays
• Special Values
• Output Data and Data Files

Ming Jiang
First Impression on MATLAB Programming

• Everything in MATLAB is an array !


• MATLAB is an interpreted language, so no compilation is needed

Matrix = Two-dimensional Array • MATLAB does NOT need:


• A collection of data values (scalars) • Variable declarations
• Organized into rows and columns • Dimension statements
• Packaging
• Storage allocation
• Pointers
• …almost nothing is
needed! …except a
computer… 

Ming Jiang www.wcomms.com 31


Example: A Simple Array

% Basic Vector or Matrix Operations


% Show how easy MATLAB is
a = [1 2 3 4 6 4 3 4 5];
b = a + 2;
plot(b);
grid on;
xlabel('Sample #');
ylabel('Pounds');

Ming Jiang www.wcomms.com 32


Naming Variables

• Variable's name:
• MUST begin with a letter
• Then followed by any combination of letters,
numbers, and the underline ( _ ) character

• The length of a variable's name SHOULD be <= 63


• Only the first 63 characters are significant
• The characters from the 64th will be ignored!

>> len = namelengthmax Examples:


len = • 4ab, _ab
63 • ID4, ID_

Ming Jiang www.wcomms.com 33


Good Practices

• Use descriptive and easy-to-remember names


Year, Month, Day are much better than a, b, c !
• Add comments on variable definitions in the
header of an M-file

• The MATLAB language is case-sensitive


name, Name, and NAME are all different!

Ming Jiang www.wcomms.com 34


Types of Variables

• The most common types of MATLAB variables are


double and char

>> var = 10.5


>> comment = 'This is a character string.' Why define
two?

• They can hold real, imaginary, or complex values


• An imaginary number is defined by appending the letter i or j
to a number

var = 4i
var = 10 + 10i

Ming Jiang www.wcomms.com 35


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 1)

• Variables and Arrays


• Initializing Variables
• Multi-dimensional Arrays and Subarrays
• Special Values
• Output Data and Data Files

Ming Jiang
Initialization of Variables

Strongly typed language


• The type of a variable must be explicitly
declared before it is used, e. g. C/C++

Weakly typed language


• Simply assigning values to variables, e.g. MATLAB

Three common methods to initialize a variable


1. Assignment statement
2. Input data from keyboard
3. Read data from a file

Ming Jiang www.wcomms.com 37


Initializing Variables in Assignment Statements (1/4)

General form of assignment statement:


var = expression

X = 1+3i;
Y = 2;
What if there is no
Var = X/2; semicolon?
Array = [1 2 3 4];

No semicolon: >> Array = [1 2 3 4]


Automatically show the
Array =
variable contents 
good for debugging! 1 2 3 4

Ming Jiang www.wcomms.com 38


Initializing Variables in Assignment Statements (2/4)

Array = 1 x 1 array = scalar


[3.4]

[1.0 2.0 3.0] 1 x 3 array = row vector

[1.0; 2.0; 3.0]


3 x 1 array = column vector
[1 2 3; 4 5 6]

[1, 2, 3; 4, 5, 6]
2 x 3 array = matrix
[1 2 3
4 5 6]

[] Empty array = ?

[1 2 3; 4 5]
?
Ming Jiang www.wcomms.com 39
Initializing Variables in Assignment Statements (3/4)

>> Array=[1 2 3; 4 5]
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Notes:
• All rows have the same number of columns
• All columns have the same number of rows

Ming Jiang www.wcomms.com 40


Initializing Variables in Assignment Statements (4/4)

• Not all the elements in an array must be defined when it is created


• If we define one element only - then all earlier elements will
automatically be created and initialized to 0

>> c(2,3) = 5 • Algebraic Extending an Array


operations • By specifying a
c = value for an
• All or portions
0 0 0
of previously element beyond the
0 0 5
defined arrays currently defined
size
>> a = [0 1+7]
a = >> d=[1 2];
0 8 >> d(4) = 4
>> b = [a(2) 7 a]
b = d =
8 7 0 8 1 2 0 4

Ming Jiang www.wcomms.com 41


Shortcut Expressions (1/2)

How to initialize an array containing many


elements?
• It is just not practical to write out each
element in the array one by one!

• Using the colon operator (:) as:


first:increment:last

>> x = 1:2.5:9
Smaller than 9
x =

1.0000 3.5000 6.0000 8.5000

Ming Jiang www.wcomms.com 42


Shortcut Expressions (2/2)

Shortcut expressions combined with the transpose operator (')

Swap the row and columns Initialize column vectors and


of any array more complex matrices

>> f = [1:4] >> h = [f' 2*f']


f =
h = 1
1 2 3 4 h =
2
1 2
3
>> g = [1:4]' What is the 2 4
4
g = use of single 3 6
2
1 colon? 4 8
4
2
How to get this? 6
3
8
4

Ming Jiang www.wcomms.com 43


Initializing Variables with Built-In Functions

Arrays can also be initialized using built-in MATLAB functions

• zeros(n); % Generates an n*n matrix of zeros


• zeros(m,n); % Generate an m*n matrix of zeros
• ones(n); % Generate an n*n matrix of ones
• ones(m,n); % Generate an m*n matrix of ones
• eye(n); % Generate an n*n identity matrix
• size(array);% Returns the numbers of rows/columns of array

>> a = zeros(2)
a = >> d = size(b); >> e = eye(3)
0 0
0 0 >> c = zeros(d) e =
Why call eye?
c =
>> b = zeros(2,3) 1 0 0
b = 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1
0 0 0

Ming Jiang www.wcomms.com 44


专业拓展小课堂:何谓眼图?

• 它是指用示波器在接收端观察到的一种图形
• 传输二进制信号波形时, 示波器上显示的图形很像
人的眼睛 ——故名“眼图”

Ming Jiang www.wcomms.com 45


Initializing Variables with Keyboard Input

Examples: input function

>> var1 = input('Enter data:');


Enter data:12.15
>> var1
var1 =
12.1500
What will
>> var2 = input('Enter data:'); happen?
Enter data:Happy Birthday!

Error: Unexpected MATLAB expression.

>> var2 = input('Enter data:','s');


Enter data:Happy Birthday!
>> var2
var2 = String
Happy Birthday!

Ming Jiang www.wcomms.com 46


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 1)

• Variables and Arrays


• Initializing Variables
• Multi-dimensional Arrays and Subarrays
• Special Values
• Output Data and Data Files

Ming Jiang
Multi-dimensional Arrays (1/2)

MATLAB can generate arrays of as many dimensions as you want


(if your computer has sufficient memory! )

What's this 1 for?

% Array c: 2×3

>> c(:,:,1) = [1 2 3;4 5 6];


>> whos c
Name Size Bytes Class Attributes

c 2x3 48 double

• whos: List all the variables in the current workspace


with more details

• who Lists the names of variables in the current workspace

Ming Jiang www.wcomms.com 48


Multi-dimensional Arrays (2/2)

% Array c: 2×3×2

>> c(:,:,2) = [7 8 9;10 11 12];


>> whos c
Name Size Bytes Class Attributes

c 2x3x2 96 double

% Array c: 2×3×2

>> c
c(:,:,1) =

The 3rd dimension 1 2 3 Old matrix


4 5 6
c(:,:,2) =
Newly added
7 8 9 matrix
10 11 12

Ming Jiang www.wcomms.com 49


Arrangement in Computer Memory
• MATLAB always allocates array elements in column major order
• 1st column  2nd column  …

>> a = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
a =
1 2 3
The 5 th element

4 5 6 in memory
7 8 9
10 11 12

• Same allocation scheme for multi-dimensional arrays


• 1st array subscript is incremented most rapidly
• 2nd subscript is incremented less rapidly
• The last subscript is incremented most slowly
• Example: the allocation order of a 2x2x2 array
• (1,1,1), (2,1,1), (1,2,1), (2,2,1), (1,1,2), (2,1,2), (1,2,2),
(2,2,2)
• The order of elements allocation in memory is
important

Ming Jiang www.wcomms.com 50


Sub-arrays

How to select a portion of an array/matrix?

>> arr = [1 2 3; -4 -5 -6; 7 8 9]

arr =
arr(1,:)
1 2 3 1 2 3
-4 -5 -6
7 8 9

3
arr(1:2:5) arr(:,3)
-6
9
1 7 -5
Not a recommended way:
easy confusion!

Ming Jiang www.wcomms.com 51


The end Function

The end function returns the highest value taken


on by that subscript

>> arr = [1 2 3 4; 5 6 7 8; 9 10 11 12]


arr =
1 2 3 4 What's the value of
5 6 7 8 this end?
9 10 11 12
arr(2:end, 2:end)=?
? What's the value of
this end?
6 7 8
10 11 12

Ming Jiang www.wcomms.com 52


Updating Sub-arrays (1/3)
Using Subarrays on the Left-Hand Side of an Assignment Statement
• The shape (the number of rows and columns) must be the same

>> arr = [1 2 3 4; 5 6 7 8; 9 10 11 12]


arr =
1 2 3 4
5 6 7 8
9 10 11 12

>> arr(1:2,[1 4]) >> arr(1:2,1:2)


ans = ans =
1 4 1 2
5 8 5 6
>> arr(1:2,[1 4]) = [20 21; 22 23] Unmatched assignment
arr =
20 2 3 21 >> arr(1:2,1:2) = [3 4]
22 6 7 23 Subscripted assignment
9 10 11 12 dimension mismatch.

Ming Jiang www.wcomms.com 53


Updating Sub-arrays (2/3)

Assigning values to a subarray v.s assigning values to an array


• Big difference!

>> arr = [1 2 3 4; 5 6 7 8; 9 10 11 12]

arr =
1 2 3 4
5 6 7 8
9 10 11 12

What's the >> arr = [20 21; 22 23]


result?

Assigning values to an arr =


array will overwrite it
completely! 20 21
22 23

Ming Jiang www.wcomms.com 54


Updating Sub-arrays (3/3)

Assigning a Scalar to a Subarray

>> arr = [1 2 3 4; 5 6 7 8; 9 10 11 12]

arr =
1 2 3 4
5 6 7 8
9 10 11 12

>> arr(1:2,1:3) = 1

arr =

1 1 1 4
1 1 1 8
9 10 11 12

Ming Jiang www.wcomms.com 55


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 1)

• Variables and Arrays


• Initializing Variables
• Multi-dimensional Arrays and Subarrays
• Special Values
• Output Data and Data Files

Ming Jiang
Special Values (1/2)

Ming Jiang www.wcomms.com 57


Special Values (2/2)
>> pi
ans = • Predefined values are stored
3.1416 in ordinary variables
• They can be overwritten
>> c = 2 * pi * 10
c = or modified by YOU!
62.8319

>> pi = 10;
>> c = 2 * pi * 10
c =
200

NEVER redefine a predefined


variable in MATLAB...

…or you may end up debugging in the rest of your life!

Ming Jiang www.wcomms.com 58


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 1)

• Variables and Arrays


• Initializing Variables
• Multi-dimensional Arrays and Subarrays
• Special Values
• Output Data and Data Files

Ming Jiang
Output Display Formats

Example: Display 12.345678901234567 in MATLAB

>> format long e, 12.345678901234567


Example ans =
1.234567890123457e+01

Ming Jiang www.wcomms.com 60


The disp Function

What does disp function do?


• Displays the value (numbers or strings) of the array in the
Command Window
• Often combined with the functions to create messages to be
displayed in the Command Window
•num2str: convert a number to a string
•int2str: convert an integer to a string

>> str = ['The value of pi = ' pi];


>> disp (str);
Wrong string displayed!
The value of pi =

>> str = ['The value of pi = ' num2str(pi)];


>> disp (str);
The value of pi = 3.1416

Ming Jiang www.wcomms.com 61


Formatted Output with the fprintf Function (1/2)

What does fprintf function do?


• Displays controllable formatted values
• General form: fprintf(format,data)

>> fprintf('The value of pi is %f \n',pi)


Examples The value of pi is 3.141593

>> fprintf('The value of pi is %6.2f \n',pi)


The value of pi is 3.14

Ming Jiang www.wcomms.com 62


Formatted Output with the fprintf Function (2/2)

The fprintf function displays only the


real part of a complex value

>> x = 2 * ( 1 - 2*i )^3;


>> str = ['disp: x = ' num2str(x)];
Complex number
>> disp(str);
disp: x = -22+4i

>> fprintf('fprintf: x = %8.4f\n',x);


fprintf: x = -22.0000

The real part only

Ming Jiang www.wcomms.com 63


Data Files (1/2)

The save function


• Save the data as MAT-files (.mat) to hard disk
• General form: save filename var1 var2 var3
• If no variables are specified, then the entire contents of the
workspace are saved

MAT-files are a good way to exchange data


• MAT-files created on any platform (PC, Mac, Unix, or Linux) can be
read on any other platform with MATLAB installed
• Can save in ASCII format

Save x.dat to
>> x=[1.23 3.14 6.28; -5.1 7.00 0];
Examples >> save -ascii x.dat x
hard disk in
ASCII format

1.2300000e+000 3.1400000e+000 6.2800000e+000 The contents of


-5.1000000e+000 7.0000000e+000 0.0000000e+000 x.dat

Ming Jiang www.wcomms.com 64


Data Files (2/2)

The load function


• Load the data from files into MATLAB's Workspace
• General form: load filename
• Load MAT-files: load –mat file.mat
• Load ASCII files: load –ascii file.dat

Example: Suppose that an ASCII file file.dat contains:


1.23 3.14 6.28
-5.1 7.00 0

>> load –ascii file.dat


>> file
create a 2x3 array
file = named file

1.230000000000000e+00 3.140000000000000e+00 6.280000000000000e+00


-5.100000000000000e+00 7.000000000000000e+00 0

Ming Jiang www.wcomms.com 65


版权说明

■ 本课程的课件
● 主要内容:本人制作
● 部分内容:参考了中山大学数据科学与计算机学院张雨浓教授
的2008年版课件
● 少量内容:参考了Kasetsart University的James Brucker博士
早期的课件
■ 下载地址:
http://www.wcomms.com/lectures/course-matlab.html

本课件及相关作业,仅限本课程教学使用
请勿上传互联网
谢谢合作!
WWW.WCOMMS.COM

You might also like