MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of...

40
MATLAB for Scientists and Engineers Numerical Computing with . Byoung-Jo CHOI, PhD University of Incheon

Transcript of MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of...

Page 1: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

MATLABfor Scientists and Engineers

Numerical Computingwith .

Byoung-Jo CHOI, PhDUniversity of Incheon

Page 2: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

2

References MATLAB Getting Started Guide, MathWorks

MATLAB User's Guide, MathWorks

Mastering MATLAB 7, Duane Hanselman and Bruce Littlefield, Pearson/Prentice Hall, 2005

Numerical Computing with MATLAB, Cleve Moler, MathWorks

임종수의 MATLAB7, 높이깊이 , 2009

MATLAB: An Introduction with Applications, Amos Gilat, John Wiley & Sons, Inc., 2004

Graphics and GUIs with MATLAB, 3rd Ed, Patrick Marchand and O. Thomas Holland, Chapman & Hall/CRC, 2003

Page 3: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

Script M-Files

Numerical Computingwith .

MATLAB for Scientists and Engineers

Page 4: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

4

You will be able to

Write simple script m-files using the editor, Get user inputs and print the formatted results, Give explanations on your scripts using com-

ments, Use cell mode for efficient coding and evalua-

tion, Create a simple dialogue window, Save and Load data to/from MATLAB data file,

text file as well as Excel files Use timer to perform repeated action

Page 5: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

5

What is Script M-File

Text file comprised of a series of MATLAB commands

The file name ends with .m, hence m-file. MATLAB interprets the lines in a script m-file. Example

calc_price.mcalc_price.m

1:2:3:4:5:

1:2:3:4:5:

% Calculate the total pricenItem = input('Enter the number of items:');uPrice = input('Enter the unit price:');tPrice = nItem * uPrice;fprintf('The total price is %d.\n', tPrice );

% Calculate the total pricenItem = input('Enter the number of items:');uPrice = input('Enter the unit price:');tPrice = nItem * uPrice;fprintf('The total price is %d.\n', tPrice );

Page 6: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

6

Launching M-File Editor 1/3

'New M-File' Toolbar

Using ToolbarUsing Toolbar

Page 7: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

7

Launching M-File Editor 2/3

'File – New – M-File' Menubar

Using MenubarUsing Menubar

Page 8: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

8

Launching M-File Editor 3/3

From Command History Window Create m-file using the past commands

Popup MenuPopup Menu

Page 9: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

9

Save and Run the Script

F5 to save the changes and

run the entire script.

Run AllRun All

SaveSave

Modified but Not Saved Yet! Modified but Not Saved Yet!*

F5F5

Page 10: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

10

Evaluate the Selected Script

F9 to run the selected script. Menubar: Text – Evaluate Section

F9 to Run theF9 to Run the Selection Using Hot KeyUsing Hot Key

Page 11: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

11

Useful Functions for Scripts

For User Interactions

beepbeep

Echo MATLAB commands in scripts.Echo MATLAB commands in scripts.echo onecho on

echo offecho off Act silently. Default mode.Act silently. Default mode.

price = input('Enter the Unit Price: ');fprintf('The price is %d.\n', price * 20 );price = input('Enter the Unit Price: ');fprintf('The price is %d.\n', price * 20 );

name = input('Enter your name: ','s');disp(name);name = input('Enter your name: ','s');disp(name);

string input

number input

pausepause pause(5)pause(5)sec waitforbuttonpresswaitforbuttonpress

keyboardkeyboard Gives control to keyboard. Go into k>> modeType R-E-T-U-R-N (5 characters) to exit.

Gives control to keyboard. Go into k>> modeType R-E-T-U-R-N (5 characters) to exit.

Debug Mode

Page 12: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

12

Getting User Inputs 1/2

Getting user input from command linegreetings_input.mgreetings_input.m

% Get user inputs using command linename = input('Your name: ','s');age = input('Your age: ');fprintf( ['Hello, %s!' ... ' You will be %d years old next year\n'], ... name, age+1);%%fprintf( 'Press key to continue..');pausetoday1 = date;fprintf( '\nToday is %s.\n', today1 );

% Get user inputs using command linename = input('Your name: ','s');age = input('Your age: ');fprintf( ['Hello, %s!' ... ' You will be %d years old next year\n'], ... name, age+1);%%fprintf( 'Press key to continue..');pausetoday1 = date;fprintf( '\nToday is %s.\n', today1 );

Page 13: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

13

Getting User Inputs 2/2

Getting user input from dialog boxgreetings_dlg.mgreetings_dlg.m

%% Get user inputs using dialogprompt = {'Your name', 'Your age:'};dlg_title = 'Greetings';num_lines = 1;def = {'Sam','21'};answer = inputdlg (prompt,dlg_title,num_lines,def);name = answer{1};age = str2num (answer{2});msg = sprintf( 'Hello, %s! You will be %d years old next year\n', name, age+1);h = msgbox (msg, 'Greetings');uiwait (h)today1 = date;msg = sprintf( '\nToday is %s.\n', today1 );h = msgbox (msg, 'Greetings');

%% Get user inputs using dialogprompt = {'Your name', 'Your age:'};dlg_title = 'Greetings';num_lines = 1;def = {'Sam','21'};answer = inputdlg (prompt,dlg_title,num_lines,def);name = answer{1};age = str2num (answer{2});msg = sprintf( 'Hello, %s! You will be %d years old next year\n', name, age+1);h = msgbox (msg, 'Greetings');uiwait (h)today1 = date;msg = sprintf( '\nToday is %s.\n', today1 );h = msgbox (msg, 'Greetings');

Page 14: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

14

Other Dialog Boxes

various_dlgs.mvarious_dlgs.mwarndlgwarndlg

errordlgerrordlg helpdlghelpdlg

questdlgquestdlg

listdlglistdlg

Page 15: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

15

Comments

Line comments

Block comments

% This m-file demonstrates filtering operation% of FIR designed for removing a tone noise.% Refer to Book1 for the exact algorithm% Three 2-R plot will be drawn.

% This m-file demonstrates filtering operation% of FIR designed for removing a tone noise.% Refer to Book1 for the exact algorithm% Three 2-R plot will be drawn.

%{This m-file demonstrates filtering operationof FIR designed for removing a tone noise.Refer to Book1 for the exact algorithm}%

%{This m-file demonstrates filtering operationof FIR designed for removing a tone noise.Refer to Book1 for the exact algorithm}%

Useful for commenting out a block of code temporarily for debugging.

Page 16: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

16

Commenting Out

Ctrl+R for commenting out the selection Ctrl+T for un-commenting out the selection

Page 17: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

17

Code Cells

Code blocks separated by %%%% Initializing Data StructureFs = 1440; % Sampling frequencyTs = 1 / Fs; % Sampling TimeF0 = 2.4e3; % Carrier frequency

%% Generate Time Domain Signalt = 0:Ts:2;s = sin(2*pi*F0*t);

%% Plot the Signalplot(t,s);

%% Initializing Data StructureFs = 1440; % Sampling frequencyTs = 1 / Fs; % Sampling TimeF0 = 2.4e3; % Carrier frequency

%% Generate Time Domain Signalt = 0:Ts:2;s = sin(2*pi*F0*t);

%% Plot the Signalplot(t,s);

Code Cell 3

Code Cell 1

Code Cell 2

Page 18: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

18

Enabling Cell Mode

When enabled, cell control toolbar appears.

Page 19: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

19

Evaluating the Cells

Run / Run & Go

Evaluate the current cell.Evaluate the current cell.

Evaluate the cell and advance to the next cell.Evaluate the cell and advance to the next cell.

CtrlCtrl EnterEnter+

CtrlCtrl ShiftShift+ EnterEnter+

Page 20: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

20

Modify Parameter and Run the Cell

Increment / decrement a parameter by Multiply / divide a parameter by

Change the value near the

cursor and execute the cell.

Change the value near the

cursor and execute the cell.

plot_cosine.mplot_cosine.m

Page 21: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

21

Output Commands - disp

disp

disp(name of a variable) or disp('text as string')disp(name of a variable) or disp('text as string')

disp_demo.mdisp_demo.m

n = [8 1 6]disp(n) % show the values of ndisp('Magic Numbers') % just textdisp(['The numbers are: ' num2str(n)]) % text and No's

n = [8 1 6]disp(n) % show the values of ndisp('Magic Numbers') % just textdisp(['The numbers are: ' num2str(n)]) % text and No's

>> disp_demon = 8 1 6 8 1 6Magic NumbersThe numbers are: 8 1 6

Page 22: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

22

Output Commands – fprintf 1/4

fprintf

fprintf('text') or fprintf('format',arg1, arg2,..)fprintf('text') or fprintf('format',arg1, arg2,..)

fprintf_demo.mfprintf_demo.m

n = [8 1 6];fprintf( '%2d %2d %2d\n', n );fprintf('Magic Numbers\nDo Exist!\n') % just textfprintf('The numbers are %d, %d and %d.\n', n)

n = [8 1 6];fprintf( '%2d %2d %2d\n', n );fprintf('Magic Numbers\nDo Exist!\n') % just textfprintf('The numbers are %d, %d and %d.\n', n)

>> fprintf_demo 8 1 6Magic NumbersDo Exist!The numbers are 8, 1 and 6.

\n new line\t horizontal tab%d decimal integer%x hexadecimal%f floating point%*d field width, ..

\n new line\t horizontal tab%d decimal integer%x hexadecimal%f floating point%*d field width, ..

Page 23: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

23

Output Commands – fprintf 2/4

fprintf understands vectors and matrices 2x multiplication table

times2_table.mtimes2_table.m

n = (1:9)';times2 = [ 2*ones(9,1) n 2*n ];fprintf('%d x %d = %2d\n', times2')

n = (1:9)';times2 = [ 2*ones(9,1) n 2*n ];fprintf('%d x %d = %2d\n', times2')

>> times2_table2 x 1 = 22 x 2 = 42 x 3 = 62 x 4 = 82 x 5 = 102 x 6 = 122 x 7 = 142 x 8 = 162 x 9 = 18

>> times2'ans = 2 2 2 2 2 2 2 2 2 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18

Page 24: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

24

Output Commands – fprintf 3/4

advanced formatting field width and precision

format_demo.mformat_demo.m

fprintf('%4d %d %5.1f %-5.1f %+5.1f\n', ... 2, 2, pi, pi, pi );fprintf('%4d %d %5.1f %-5.1f %+5.1f\n', ... -2, -2, -pi, -pi, -pi );

fprintf('%4d %d %5.1f %-5.1f %+5.1f\n', ... 2, 2, pi, pi, pi );fprintf('%4d %d %5.1f %-5.1f %+5.1f\n', ... -2, -2, -pi, -pi, -pi );

>> format_demo 2 2 3.1 3.1 +3.1 -2 -2 -3.1 -3.1 -3.1

22 22 33 .. 11 33 .. 11

-- 22 -- 22 -- 33 .. 11 -- 33 .. 11

++ 33 .. 11

-- 33 .. 11

Page 25: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

25

Output Commands – fprintf 4/4

Writing into a text file Steps:

times2_table_file.mtimes2_table_file.m

n = (1:9)';times2 = [ 2*ones(9,1) n 2*n ];fid = fopen('times2.txt','w');fprintf(fid, '%d x %d = %2d\n', times2');fclose(fid);

n = (1:9)';times2 = [ 2*ones(9,1) n 2*n ];fid = fopen('times2.txt','w');fprintf(fid, '%d x %d = %2d\n', times2');fclose(fid);

fopen() fprintf() fclose()

times2.txttimes2.txt

Page 26: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

26

MATLAB Data File

save and load into/from MATLAB data file save

load

save mydatasave mydata

save mydata var1 var2 ...save mydata var1 var2 ...

save mydata var3 -appendsave mydata var3 -append

save –ascii mydata.txt var1save –ascii mydata.txt var1

load mydataload mydata

load mydata.txtload mydata.txt

Page 27: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

27

Reading from Excel File 1/2

xlsread Interactive range selection

a = xlsread('simple.xlsx',-1)a = xlsread('simple.xlsx',-1)

Page 28: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

28

Reading from Excel File 2/2

xlsread Read the entire excel file

Read a range of data from the excel file

a = xlsread('simple.xlsx')a = xlsread('simple.xlsx')

a = xlsread('simple.xlsx','Sheet1','A3:B4')a = xlsread('simple.xlsx','Sheet1','A3:B4')

Page 29: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

29

Writing to Excel File

xlswrite Write data into an Excel file.

xlswrite_demo.mxlswrite_demo.m

% Excel write demo% Write to the first sheet beginning from A1xlswrite('magic.xlsx', magic(4));% Write to a new sheet, 'Magic5', beginning from A1xlswrite('magic.xlsx', magic(5), 'Magic5');% Write to 'Sheet2' beginning from A1xlswrite('magic.xlsx', magic(6), 2);% Write to 'Sheet3' beginning from B2xlswrite('magic.xlsx', magic(7), 3, 'B2');

% Excel write demo% Write to the first sheet beginning from A1xlswrite('magic.xlsx', magic(4));% Write to a new sheet, 'Magic5', beginning from A1xlswrite('magic.xlsx', magic(5), 'Magic5');% Write to 'Sheet2' beginning from A1xlswrite('magic.xlsx', magic(6), 2);% Write to 'Sheet3' beginning from B2xlswrite('magic.xlsx', magic(7), 3, 'B2');

Page 30: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

30

repeated_hello.mrepeated_hello.m

t = timer('TimerFcn','say_hello','StartDelay',2, 'ExecutionMode','fixedDelay','Period', 3);

t = timer('TimerFcn','say_hello','StartDelay',2, 'ExecutionMode','fixedDelay','Period', 3);

Timer

Repeated action using timer function

StartDelayPeriod Period Period

start(t)start(t)

stop(t)stop(t) delete(t)delete(t)

fixedRate fixedSpacingsingleShot

say_hello.msay_hello.m

function say_helloload voicessoundsc(hello,Fs)

function say_helloload voicessoundsc(hello,Fs) Try timer_demo.m!!Try timer_demo.m!!

Page 31: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

31

Timer Demo

A man says 'Hello!' repeatedly.timer_demo.mtimer_demo.m

% Timer demonstrationans = inputdlg('Period in seconds', ... 'Greeting Man Timer',1,{'3'});period = str2double(ans{1});t = timer('TimerFcn','say_hello','StartDelay',1, ... 'ExecutionMode','fixedDelay','Period', period);start(t);%% Listen to the voice for a while.h = msgbox('Do you want to stop the timer?' , ... 'Stop Timer');uiwait(h);stop(t)delete(t)

% Timer demonstrationans = inputdlg('Period in seconds', ... 'Greeting Man Timer',1,{'3'});period = str2double(ans{1});t = timer('TimerFcn','say_hello','StartDelay',1, ... 'ExecutionMode','fixedDelay','Period', period);start(t);%% Listen to the voice for a while.h = msgbox('Do you want to stop the timer?' , ... 'Stop Timer');uiwait(h);stop(t)delete(t)

Page 32: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

32

Start-up and Finish Script

User defined: startup.m, finish.m

matlabrc.mmatlabrc.m

pathdef.mpathdef.m

startup.mstartup.m

finish.mfinish.m

MATLAB

format compactcd c:\workformat compactcd c:\work

q='Sure?';b=questdlg(q,'Exit

Request','Yes','No','No');switch bcase 'No;

quit cancel;end

q='Sure?';b=questdlg(q,'Exit

Request','Yes','No','No');switch bcase 'No;

quit cancel;end

edit startupsav.medit startupsav.m

Page 33: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

33

Exercise 1 – Prime Factoring v1.0

Write a script file, 'ifactor.m', which gets a number from user and prints the number as a product of the prime factors. (Hint: factor)

>> ifactorPrime Factoring v1.0Enter a positive integer:3030 = 1 x 2 x 3 x 5>> ifactorPrime Factoring v1.0Enter a positive integer:4040 = 1 x 2 x 2 x 2 x 5

Page 34: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

34

Solution 1

Script

Screenshot of running 'ifactor'

ifactor.mifactor.m

Page 35: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

35

Exercise 2 – Prime Factoring v1.1

Write a script file, 'ifactor2.m', which gets a number from user using a dialog box and prints the number as a product of the prime factors at a message box.

[Hint: inputdlg(), msgbox()]

Page 36: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

36

Solution 2

Script and Screenshotifactor2.mifactor2.m

Page 37: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

37

Exercise 3 – Mean and Variance

Write a script file, 'icalc.m', which prints the mean and the variance of the data in 'mark-s.xlsx'.

[Hint: mean(), var()]

Page 38: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

38

Solution 3

Script

Screenshot of running icalc

icalc.micalc.m

Page 39: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

39

Notes

Page 40: MATLAB for Scientists and Engineers Numerical Computing with. Byoung-Jo CHOI, PhD University of Incheon.

40

Notes