1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

MATLAB programming fundamentals

1,1K 445 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

MATLAB® Programming Fundamentals R2015b How to Contact MathWorks Latest news: www.mathworks.com Sales and services: www.mathworks.com/sales_and_services User community: www.mathworks.com/matlabcentral Technical support: www.mathworks.com/support/contact_us Phone: 508-647-7000 The MathWorks, Inc Apple Hill Drive Natick, MA 01760-2098 MATLAB Programming Fundamentals © COPYRIGHT 1984–2015 by The MathWorks, Inc The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014 Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions If this License fails to meet the government's needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc Trademarks MATLAB and Simulink are registered trademarks of The MathWorks, Inc See www.mathworks.com/trademarks for a list of additional trademarks Other product or brand names may be trademarks or registered trademarks of their respective holders Patents MathWorks products are protected by one or more U.S patents Please see www.mathworks.com/patents for more information Revision History June 2004 October 2004 March 2005 June 2005 September 2005 March 2006 September 2006 March 2007 September 2007 March 2008 October 2008 March 2009 September 2009 March 2010 September 2010 April 2011 September 2011 March 2012 September 2012 March 2013 September 2013 March 2014 October 2014 March 2015 September 2015 First printing Online only Online only Second printing Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only Online only New for MATLAB 7.0 (Release 14) Revised for MATLAB 7.0.1 (Release 14SP1) Revised for MATLAB 7.0.4 (Release 14SP2) Minor revision for MATLAB 7.0.4 Revised for MATLAB 7.1 (Release 14SP3) Revised for MATLAB 7.2 (Release 2006a) Revised for MATLAB 7.3 (Release 2006b) Revised for MATLAB 7.4 (Release 2007a) Revised for Version 7.5 (Release 2007b) Revised for Version 7.6 (Release 2008a) Revised for Version 7.7 (Release 2008b) Revised for Version 7.8 (Release 2009a) Revised for Version 7.9 (Release 2009b) Revised for Version 7.10 (Release 2010a) Revised for Version 7.11 (Release 2010b) Revised for Version 7.12 (Release 2011a) Revised for Version 7.13 (Release 2011b) Revised for Version 7.14 (Release 2012a) Revised for Version 8.0 (Release 2012b) Revised for Version 8.1 (Release 2013a) Revised for Version 8.2 (Release 2013b) Revised for Version 8.3 (Release 2014a) Revised for Version 8.4 (Release 2014b) Revised for Version 8.5 (Release 2015a) Revised for Version 8.6 (Release 2015b) Contents Language Syntax Basics Create Variables 1-2 Create Numeric Arrays 1-3 Continue Long Statements on Multiple Lines 1-5 Call Functions 1-6 Ignore Function Outputs 1-7 Variable Names Valid Names Conflicts with Function Names 1-8 1-8 1-8 Case and Space Sensitivity 1-10 Command vs Function Syntax Command and Function Syntaxes Avoid Common Syntax Mistakes How MATLAB Recognizes Command Syntax 1-12 1-12 1-13 1-14 Common Errors When Calling Functions Conflicting Function and Variable Names Undefined Functions or Variables 1-16 1-16 1-16 v vi Contents Program Components Array vs Matrix Operations Introduction Array Operations Matrix Operations 2-2 2-2 2-2 2-4 Relational Operators Relational Operators and Arrays Relational Operators and Empty Arrays 2-7 2-7 2-7 Operator Precedence Precedence of AND and OR Operators Overriding Default Precedence 2-9 2-9 2-9 Average Similar Data Points Using a Tolerance 2-11 Group Scattered Data Using a Tolerance 2-14 Special Values 2-17 Conditional Statements 2-19 Loop Control Statements 2-21 Regular Expressions What Is a Regular Expression? Steps for Building Expressions Operators and Characters 2-23 2-23 2-25 2-28 Lookahead Assertions in Regular Expressions Lookahead Assertions Overlapping Matches Logical AND Conditions 2-39 2-39 2-39 2-40 Tokens in Regular Expressions Introduction Multiple Tokens Unmatched Tokens Tokens in Replacement Strings Named Capture 2-42 2-42 2-43 2-44 2-45 2-45 Dynamic Regular Expressions Introduction Dynamic Match Expressions — (??expr) Commands That Modify the Match Expression — (?? @cmd) Commands That Serve a Functional Purpose — (? @cmd) Commands in Replacement Expressions — ${cmd} 2-51 2-53 Comma-Separated Lists What Is a Comma-Separated List? Generating a Comma-Separated List Assigning Output from a Comma-Separated List Assigning to a Comma-Separated List How to Use the Comma-Separated Lists Fast Fourier Transform Example 2-56 2-56 2-56 2-58 2-59 2-61 2-63 Alternatives to the eval Function Why Avoid the eval Function? Variables with Sequential Names Files with Sequential Names Function Names in Variables Field Names in Variables Error Handling 2-65 2-65 2-65 2-66 2-67 2-67 2-68 Symbol Reference Asterisk — * At — @ Colon — : Comma — , Curly Braces — { } Dot — Dot-Dot — Dot-Dot-Dot (Ellipsis) — Dot-Parentheses — ( ) Exclamation Point — ! Parentheses — ( ) Percent — % Percent-Brace — %{ %} Plus — + Semicolon — ; Single Quotes — ' ' Space Character Slash and Backslash — / \ 2-69 2-69 2-70 2-71 2-72 2-72 2-73 2-73 2-74 2-75 2-75 2-75 2-76 2-76 2-77 2-77 2-78 2-78 2-79 2-48 2-48 2-49 2-50 vii Square Brackets — [ ] Tilde — ~ 2-79 2-80 Classes (Data Types) Overview of MATLAB Classes Fundamental MATLAB Classes viii Contents 3-2 Numeric Classes Integers Integer Classes Creating Integer Data Arithmetic Operations on Integer Classes Largest and Smallest Values for Integer Classes Integer Functions 4-2 4-2 4-3 4-4 4-5 4-5 Floating-Point Numbers Double-Precision Floating Point Single-Precision Floating Point Creating Floating-Point Data Arithmetic Operations on Floating-Point Numbers Largest and Smallest Values for Floating-Point Classes Accuracy of Floating-Point Data Avoiding Common Problems with Floating-Point Arithmetic Floating-Point Functions References 4-6 4-6 4-6 4-7 4-8 4-9 4-11 Complex Numbers Creating Complex Numbers Complex Number Functions 4-16 4-16 4-17 4-12 4-14 4-14 Infinity and NaN Infinity NaN Infinity and NaN Functions 4-18 4-18 4-18 4-20 Identifying Numeric Classes 4-21 Display Format for Numeric Values Default Display Display Format Examples Setting Numeric Format in a Program 4-22 4-22 4-22 4-23 Function Summary 4-25 The Logical Class Find Array Elements That Meet a Condition Apply a Single Condition Apply Multiple Conditions Replace Values that Meet a Condition 5-2 5-2 5-4 5-5 Determine if Arrays Are Logical Identify Logical Matrix Test an Entire Array Test Each Array Element Summary Table 5-7 5-7 5-7 5-8 5-9 Reduce Logical Arrays to Single Value 5-10 Truth Table for Logical Operations 5-13 Characters and Strings Creating Character Arrays Creating a Character String 6-2 6-2 ix x Contents Creating a Rectangular Character Array Identifying Characters in a String Working with Space Characters Expanding Character Arrays 6-3 6-4 6-5 6-6 Cell Arrays of Strings Converting to a Cell Array of Strings Functions for Cell Arrays of Strings 6-7 6-7 6-8 Formatting Strings Functions that Use Format Strings The Format String Input Value Arguments The Formatting Operator Constructing the Formatting Operator Setting Field Width and Precision Restrictions for Using Identifiers 6-10 6-10 6-11 6-12 6-13 6-14 6-19 6-21 String Comparisons Comparing Strings for Equality Comparing for Equality Using Operators Categorizing Characters Within a String 6-23 6-23 6-24 6-24 Searching and Replacing 6-26 Converting from Numeric to String Function Summary Converting to a Character Equivalent Converting to a String of Numbers Converting to a Specific Radix 6-28 6-28 6-29 6-29 6-29 Converting from String to Numeric Function Summary Converting from a Character Equivalent Converting from a Numeric String Converting from a Specific Radix 6-30 6-30 6-30 6-31 6-31 Function Summary 6-33 30 Unit Testing function setupMethod1(testCase) testCase.assumeEqual(1,0) % remaining test code is not exercised end function setupMethod2(testCase) disp('* Running setupMethod2 *') testCase.assertEqual(1,1) end end methods(Test) function testA(testCase) testCase.verifyTrue(true) end function testB(testCase) testCase.assumeEqual(0,1) % remaining test code is not exercised end function testC(testCase) testCase.verifyFalse(true) end end end When you run the test, you see that the framework does not execute any of the methods in the TestMethodSetup or Test ts = matlab.unittest.TestSuite.fromClass(?ExampleTest); res = ts.run; Running ExampleTest ================================================================================ All tests in ExampleTest were filtered Details ================================================================================ Done ExampleTest Failure Summary: Name Failed Incomplete Reason(s) ================================================================ ExampleTest/testA X Filtered by assumption 30-124 Dynamically Filtered Tests -ExampleTest/testB X Filtered by assumption -ExampleTest/testC X Filtered by assumption The Test and TestMethodSetup methods did not change but everything is filtered due to an assumption failure in the TestClassSetup block See Also matlab.unittest.qualifications.Assumable | TestCase | TestResult 30-125 30 Unit Testing Create Custom Constraint This example shows how to create a custom constraint that determines if a given value is the same size as an expected value In a file in your working folder, create a HasSameSizeAs.m The constructor accepts a value to compare to the actual size This value is stored within the ValueWithExpectedSize property Since, it is recommended that Constraint implementations are immutable, set the property SetAccess=immutable classdef HasSameSizeAs < matlab.unittest.constraints.Constraint properties(SetAccess=immutable) ValueWithExpectedSize end methods function constraint = HasSameSizeAs(value) constraint.ValueWithExpectedSize = value; end end end Classes that derive from Constraint must implement the satisfiedBy method This method must contain the comparison logic and return a boolean value Include the satisfiedBy method in the methods block in HasSameSizeAs.m function bool = satisfiedBy(constraint, actual) bool = isequal(size(actual), size(constraint.ValueWithExpectedSize)); end If the actual size and expected size are equal, this method returns true Classes deriving from Constraint must implement the getDiagnosticFor method This method must evaluate the actual value against the constraint and provide a Diagnostic object In this example, getDiagnosticFor returns a StringDiagnostic Include the getDiagnosticFor method in the methods block in HasSameSizeAs.m function diag = getDiagnosticFor(constraint, actual) import matlab.unittest.diagnostics.StringDiagnostic 30-126 Create Custom Constraint if constraint.satisfiedBy(actual) diag = StringDiagnostic('HasSameSizeAs passed.'); else diag = StringDiagnostic(sprintf( 'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]', int2str(size(actual)), int2str(size(constraint.ValueWithExpectedSize)))); end end HasSameSizeAs Class Definition Summary classdef HasSameSizeAs < matlab.unittest.constraints.Constraint properties(SetAccess=immutable) ValueWithExpectedSize end methods function constraint = HasSameSizeAs(value) constraint.ValueWithExpectedSize = value; end function bool = satisfiedBy(constraint, actual) bool = isequal(size(actual), size(constraint.ValueWithExpectedSize)); end function diag = getDiagnosticFor(constraint, actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.satisfiedBy(actual) diag = StringDiagnostic('HasSameSizeAs passed.'); else diag = StringDiagnostic(sprintf( 'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]', int2str(size(actual)), int2str(size(constraint.ValueWithExpectedSize)))); end end end end At the command prompt, create a test case for interactive testing import matlab.unittest.TestCase testCase = TestCase.forInteractiveUse; Test a passing case testCase.verifyThat(zeros(5), HasSameSizeAs(repmat(1,5))) Interactive verification passed Test a failing case 30-127 30 Unit Testing testCase.verifyThat(zeros(5), HasSameSizeAs(ones(1,5))) Interactive verification failed Framework Diagnostic: HasSameSizeAs failed Actual Size: [5 5] ExpectedSize: [1 5] See Also matlab.unittest.constraints.Constraint Related Examples • 30-128 “Create Custom Boolean Constraint” on page 30-129 Create Custom Boolean Constraint Create Custom Boolean Constraint This example shows how to create a custom boolean constraint that determines if a given value is the same size as an expected value In a file in your working folder, create a file HasSameSizeAs.m The constructor accepts a value to compare to the actual size This value is stored within the ValueWithExpectedSize property It is recommended that BooleanConstraint implementations be immutable, so set the property SetAccess=immutable classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint properties(SetAccess=immutable) ValueWithExpectedSize end methods function constraint = HasSameSizeAs(value) constraint.ValueWithExpectedSize = value; end end end Include these methods in the methods block in HasSameSizeAs.m Since the BooleanConstraint class is a subclass of Constraint, classes that derive from it must implement the satisfiedBy and getDiagnosticFor methods For more information about these methods, see matlab.unittest.constraints.Constraint methods function bool = satisfiedBy(constraint, actual) bool = isequal(size(actual), size(constraint.ValueWithExpectedSize)); end function diag = getDiagnosticFor(constraint, actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.satisfiedBy(actual) diag = StringDiagnostic('HasSameSizeAs passed.'); else diag = StringDiagnostic(sprintf( 'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]', int2str(size(actual)), int2str(size(constraint.ValueWithExpectedSize)))); end end end Include the getNegativeDiagnosticFor method in the methods block with protected access in HasSameSizeAs.m Classes that derive from BooleanConstraint must implement the getNegativeDiagnosticFor method This method must provide a Diagnostic object that is expressed in the negative sense of the constraint methods(Access=protected) function diag = getNegativeDiagnosticFor(constraint, actual) 30-129 30 Unit Testing import matlab.unittest.diagnostics.StringDiagnostic if constraint.satisfiedBy(actual) diag = StringDiagnostic(sprintf( ['Negated HasSameSizeAs failed.\nSize [%s] of ' 'Actual Value and Expected Value were the same ' 'but should not have been.'], int2str(size(actual)))); else diag = StringDiagnostic('Negated HasSameSizeAs passed.'); end end end In exchange for implementing the required methods, the constraint inherits the appropriate and, or, and not overloads so it can be combined with other BooleanConstraint objects or negated HasSameSizeAs Class Definition Summary classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint properties(SetAccess=immutable) ValueWithExpectedSize end methods function constraint = HasSameSizeAs(value) constraint.ValueWithExpectedSize = value; end function bool = satisfiedBy(constraint, actual) bool = isequal(size(actual), size(constraint.ValueWithExpectedSize)); end function diag = getDiagnosticFor(constraint, actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.satisfiedBy(actual) diag = StringDiagnostic('HasSameSizeAs passed.'); else diag = StringDiagnostic(sprintf( 'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]', int2str(size(actual)), int2str(size(constraint.ValueWithExpectedSize)))); end end end methods(Access=protected) function diag = getNegativeDiagnosticFor(constraint, actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.satisfiedBy(actual) diag = StringDiagnostic(sprintf( ['Negated HasSameSizeAs failed.\nSize [%s] of ' 'Actual Value and Expected Value were the same ' 'but should not have been.'], int2str(size(actual)))); else diag = StringDiagnostic('Negated HasSameSizeAs passed.'); end end end end At the command prompt, create a test case for interactive testing 30-130 Create Custom Boolean Constraint import matlab.unittest.TestCase import matlab.unittest.constraints.HasLength testCase = TestCase.forInteractiveUse; Test a passing case testCase.verifyThat(zeros(5), HasLength(5) | ~HasSameSizeAs(repmat(1,5))) Interactive verification passed The test passes because one of the or conditions, HasLength(5), is true Test a failing case testCase.verifyThat(zeros(5), HasLength(5) & ~HasSameSizeAs(repmat(1,5))) Interactive verification failed Framework Diagnostic: AndConstraint failed > + [First Condition]: | HasLength passed > AND + [Second Condition]: | Negated HasSameSizeAs failed | Size [5 5] of Actual Value and Expected Value were the same but should not -+ - The test fails because one of the and conditions, ~HasSameSizeAs(repmat(1,5)), is false See Also matlab.unittest.constraints.BooleanConstraint Related Examples • “Create Custom Constraint” on page 30-126 30-131 30 Unit Testing Create Custom Tolerance This example shows how to create a custom tolerance to determine if two DNA sequences have a Hamming distance within a specified tolerance For two DNA sequences (strings) of the same length, the Hamming distance is the number of positions in which the nucleotides (letters) of one sequence differ from the other In a file, DNA.m, in your working folder, create a simple class for a DNA sequence classdef DNA properties(SetAccess=immutable) Sequence end methods function dna = DNA(sequence) validLetters = sequence == 'A' | sequence == 'C' | sequence == 'T' | sequence == 'G'; if ~all(validLetters(:)) error('Sequence contained a letter not found in DNA.') end dna.Sequence = sequence; end end end In a file in your working folder, create a tolerance class so that you can test that DNA sequences are within a specified Hamming distance The constructor requires a Value property that defines the maximum Hamming distance classdef HammingDistance < matlab.unittest.constraints.Tolerance properties Value end methods function tolerance = HammingDistance(value) tolerance.Value = value; end 30-132 Create Custom Tolerance end end In a methods block with the HammingDistance class definition, include the following method so that the tolerance supports DNA objects Tolerance classes must implement a supports method methods function tf = supports(~, value) tf = isa(value, 'DNA'); end end In a methods block with the HammingDistance class definition, include the following method that returns true or false Tolerance classes must implement a satisfiedBy method The testing framework uses this method to determine if two values are within the tolerance methods function tf = satisfiedBy(tolerance, actual, expected) if ~isSameSize(actual.Sequence, expected.Sequence) tf = false; return end tf = hammingDistance(actual.Sequence,expected.Sequence) The objects are not equal using "isequal" Actual Object: DNA with properties: Sequence: 'ACCTGAGTA' Expected Object: DNA with properties: Sequence: 'ACCACAGTA' Verify that the DNA sequences are equal to each other within a Hamming distance of testCase.verifyThat(sampleA, IsEqualTo(sampleB, 'Within', HammingDistance(1))) Interactive verification failed Framework Diagnostic: IsEqualTo failed > ObjectComparator failed > The objects are not equal using "isequal" > The DNA sequences have a Hamming distance of The allowable distance is Actual Object: DNA with properties: Sequence: 'ACCTGAGTA' Expected Object: DNA with properties: Sequence: 'ACCACAGTA' The sequences are not equal to each other within a tolerance of The testing framework displays additional diagnostics from the getDiagnosticFor method Verify that the DNA sequences are equal to each other within a Hamming distance of testCase.verifyThat(sampleA, IsEqualTo(sampleB, 'Within', HammingDistance(2))) 30-136 Create Custom Tolerance Interactive verification passed See Also matlab.unittest.constraints.Tolerance 30-137 [...]... 21-29 21-29 21-30 21-31 21-33 21-37 21-39 Create a MATLAB Notebook with Microsoft Word Getting Started with MATLAB Notebooks Creating and Evaluating Cells in a MATLAB Notebook Formatting a MATLAB Notebook Tips for Using MATLAB Notebooks Configuring the MATLAB Notebook Software 21-43 21-43 21-45 21-50 21-52 21-53... Double Types 15 14-9 14-9 14-9 14-10 14-10 Using Objects MATLAB Objects Getting Oriented What Are Objects and Why Use Them? Working with Objects Objects In the MATLAB Language Other Kinds of Objects Used by MATLAB 15-2 15-2 15-2 15-3 15-3 15-3 General Purpose Vs Specialized... Select Workspace View Variable Value 20-17 20-17 20-17 Presenting MATLAB Code Options for Presenting Your Code 21-2 Document and Share Code Using Examples 21-4 Publishing MATLAB Code 21-7 Publishing Markup Markup Overview 21-9... 19-13 Check Function Inputs with validateattributes 19-14 20 21 Parse Function Inputs 19-17 Input Parser Validation Functions 19-21 Debugging MATLAB Code Debug a MATLAB Program Set Breakpoint Find and Fix a Problem Step Through File End Debugging Session... a File Simultaneously 22-39 Add Reminders to Files Working with TODO/FIXME Reports 22-41 22-41 Colors in the MATLAB Editor 22-44 Code Contains %#ok — What Does That Mean? 22-46 MATLAB Code Analyzer Report Running the Code Analyzer Report Changing Code Based on Code Analyzer Messages Other Ways to Access... 26-13 Techniques to Improve Performance Environment Code Structure 26-15 26-15 26-15 27 Programming Practices for Performance Tips on Specific MATLAB Functions 26-15 26-16 Preallocation Preallocating a Nondouble Matrix 26-18 26-18 Vectorization ... Interface 29-43 Set Up MSSCCI Source Control Create Projects in Source Control System Specify Source Control System with MATLAB Software Register Source Control Project with MATLAB Software Add Files to Source Control 29-44 29-44 Check Files In and Out from MSSCCI Source Control... Class of Workspace Variables Information About Class Members Logical Tests for Objects Displaying Objects Getting Help for MATLAB Objects 15-20 15-20 15-22 15-22 15-23 15-24 Copying Objects Two Copy Behaviors Value Object Copy Behavior ... 22-47 22-47 22-49 22-50 22-23 22-28 xxiii Change Default Editor Set Default Editor Set Default Editor in '-nodisplay' mode 22-51 22-51 22-51 Programming Utilities 23 Identify Program Dependencies Simple Display of Program File Dependencies Detailed Display of Program File Dependencies Dependencies Within a Folder... Toolboxes Create Toolbox Share Toolbox 23-13 23-13 23-16 Software Development 24 Error Handling Exception Handling in a MATLAB Application Overview Getting an Exception at the Command Line Getting an Exception in Your Program Code xxiv Contents 24-2 24-2 24-2 24-3 ... for MATLAB 7.0 (Release 14) Revised for MATLAB 7.0.1 (Release 14SP1) Revised for MATLAB 7.0.4 (Release 14SP2) Minor revision for MATLAB 7.0.4 Revised for MATLAB 7.1 (Release 14SP3) Revised for MATLAB. .. www.mathworks.com/matlabcentral Technical support: www.mathworks.com/support/contact_us Phone: 508-647-7000 The MathWorks, Inc Apple Hill Drive Natick, MA 01760-2098 MATLAB Programming Fundamentals. .. Create a MATLAB Notebook with Microsoft Word Getting Started with MATLAB Notebooks Creating and Evaluating Cells in a MATLAB Notebook Formatting a MATLAB

Ngày đăng: 06/02/2016, 08:23

TỪ KHÓA LIÊN QUAN