1 / 40

420 likes | 631 Vues

MATLAB for Scientists and Engineers. Numerical Computing with . Byoung -Jo CHOI, PhD University of Incheon. References. MATLAB Getting Started Guide, MathWorks MATLAB User's Guide, MathWorks

Télécharger la présentation
## MATLAB for Scientists and Engineers

**An Image/Link below is provided (as is) to download presentation**
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.
Content is provided to you AS IS for your information and personal use only.
Download presentation by click this link.
While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.
During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

**MATLABfor Scientists and Engineers**Numerical Computing with . Byoung-Jo CHOI, PhD University of Incheon**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**Script M-Files**Numerical Computing with . MATLAB for Scientists and Engineers**You will be able to**• Write simple scriptm-files using the editor, • Get user inputs and print the formatted results, • Give explanations on your scripts using comments, • Use cell mode for efficient coding and evaluation, • Create a simple dialoguewindow, • Save and Load data to/from MATLAB data file, text file as well as Excel files • Use timer to perform repeated action**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.m 1: 2: 3: 4: 5: % Calculate the total price nItem = input('Enter the number of items:'); uPrice = input('Enter the unit price:'); tPrice = nItem * uPrice; fprintf('The total price is %d.\n', tPrice);**Launching M-File Editor 1/3**• 'New M-File' Toolbar Using Toolbar**Launching M-File Editor 2/3**• 'File – New – M-File' Menubar Using Menubar**Launching M-File Editor 3/3**• From Command History Window • Create m-file using the past commands Popup Menu**Save and Run the Script**• F5 to save the changes and run the entire script. Modified but Not Saved Yet! * Save Run All F5**Evaluate the Selected Script**• F9 to run the selected script. • Menubar: Text – Evaluate Section Using Hot Key F9 to Run the Selection**Useful Functions for Scripts**• For User Interactions beep pause pause(5) waitforbuttonpress sec echo on Echo MATLAB commands in scripts. echo off Act silently. Default mode. price = input('Enter the Unit Price: '); fprintf('The price is %d.\n', price * 20 ); number input name = input('Enter your name: ','s'); disp(name); string input keyboard Gives control to keyboard. Go into k>> mode Type R-E-T-U-R-N (5 characters) to exit. Debug Mode**Getting User Inputs 1/2**• Getting user input from command line greetings_input.m % Get user inputs using command line name = 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..'); pause today1 = date; fprintf( '\nToday is %s.\n', today1 );**Getting User Inputs 2/2**• Getting user input from dialog box greetings_dlg.m %% Get user inputs using dialog prompt = {'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');**Other Dialog Boxes**errordlg helpdlg questdlg listdlg warndlg various_dlgs.m**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 }% Useful for commenting out a block of code temporarily for debugging.**Commenting Out**• Ctrl+R for commenting out the selection • Ctrl+T for un-commenting out the selection**Code Cells**• Code blocks separated by %% %% Initializing Data Structure Fs = 1440; % Sampling frequency Ts = 1 / Fs; % Sampling Time F0 = 2.4e3; % Carrier frequency %% Generate Time Domain Signal t = 0:Ts:2; s = sin(2*pi*F0*t); %% Plot the Signal plot(t,s); Code Cell 1 Code Cell 2 Code Cell 3**Enabling Cell Mode**• When enabled, cell control toolbar appears.**Evaluating the Cells**• Run / Run & Go Ctrl Shift Enter + + Evaluate the cell and advance to the next cell. Ctrl Enter Evaluate the current cell. +**Modify Parameter and Run the Cell**• Increment / decrement a parameter by • Multiply / divide a parameter by plot_cosine.m Change the value near the cursor and execute the cell.**Output Commands - disp**• disp disp(name of a variable) ordisp('text as string') disp_demo.m n = [8 1 6] disp(n) % show the values of n disp('Magic Numbers') % just text disp(['The numbers are: ' num2str(n)]) % text and No's >> disp_demo n = 8 1 6 8 1 6 Magic Numbers The numbers are: 8 1 6**Output Commands – fprintf 1/4**• fprintf fprintf('text') orfprintf('format',arg1, arg2,..) fprintf_demo.m n = [8 1 6]; fprintf( '%2d %2d %2d\n', n ); fprintf('Magic Numbers\nDo Exist!\n') % just text fprintf('The numbers are %d, %d and %d.\n', n) >> fprintf_demo 8 1 6 Magic Numbers Do 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, ..**Output Commands – fprintf 2/4**• fprintf understands vectors and matrices • 2x multiplication table >> times2_table 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 times2_table.m n = (1:9)'; times2 = [ 2*ones(9,1) n 2*n ]; fprintf('%d x %d = %2d\n', times2') >> 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**Output Commands – fprintf 3/4**• advanced formatting • field width and precision format_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 ); >> format_demo 2 2 3.1 3.1 +3.1 -2 -2 -3.1 -3.1 -3.1 2 2 3 . 1 3 . 1 + 3 . 1 - 2 - 2 - 3 . 1 - 3 . 1 - 3 . 1**Output Commands – fprintf 4/4**• Writing into a text file • Steps: fopen() fprintf() fclose() times2_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); times2.txt**MATLAB Data File**• save and load into/from MATLAB data file • save • load savemydata savemydata var1 var2 ... savemydata var3 -append save –ascii mydata.txt var1 loadmydata load mydata.txt**Reading from Excel File 1/2**• xlsread • Interactive range selection a = xlsread('simple.xlsx',-1)**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','Sheet1','A3:B4')**Writing to Excel File**• xlswrite • Write data into an Excel file. xlswrite_demo.m % Excel write demo % Write to the first sheet beginning from A1 xlswrite('magic.xlsx', magic(4)); % Write to a new sheet, 'Magic5', beginning from A1 xlswrite('magic.xlsx', magic(5), 'Magic5'); % Write to 'Sheet2' beginning from A1 xlswrite('magic.xlsx', magic(6), 2); % Write to 'Sheet3' beginning from B2 xlswrite('magic.xlsx', magic(7), 3, 'B2');**Timer**• Repeated action using timer function repeated_hello.m t = timer('TimerFcn','say_hello','StartDelay',2, 'ExecutionMode','fixedDelay','Period', 3); start(t) fixedRate singleShot fixedSpacing stop(t) delete(t) StartDelay Period Period Period say_hello.m function say_hello load voices soundsc(hello,Fs) Try timer_demo.m!!**Timer Demo**• A man says 'Hello!' repeatedly. timer_demo.m % Timer demonstration ans = 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)**Start-up and Finish Script**• User defined: startup.m, finish.m MATLAB matlabrc.m finish.m q='Sure?'; b=questdlg(q,'Exit Request','Yes','No','No'); switch b case 'No; quit cancel; end startup.m format compact cd c:\work pathdef.m edit startupsav.m**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) >> ifactor Prime Factoring v1.0 Enter a positive integer:30 30 = 1 x 2 x 3 x 5 >> ifactor Prime Factoring v1.0 Enter a positive integer:40 40 = 1 x 2 x 2 x 2 x 5**Solution 1**• Script • Screenshot of running 'ifactor' ifactor.m**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()]**Solution 2**• Script and Screenshot ifactor2.m**Exercise 3 – Mean and Variance**• Write a script file, 'icalc.m', which prints the mean and the variance of the data in 'marks.xlsx'. [Hint: mean(), var()]**Solution 3**• Script • Screenshot of running icalc icalc.m

More Related