This document provides a 3 sentence summary of a short term training program on Matlab for beginners:
The training program covers basic Matlab topics like the desktop interface, variables, arithmetic operations, matrices and arrays. It explains how to create and manipulate numeric data, perform common operations element-wise and on whole matrices, and generate matrices using functions. The document also demonstrates how to index and slice arrays to access subsets of elements and concatenate arrays horizontally and vertically.
This document provides an introduction and overview of MATLAB. It discusses the MATLAB environment, how to get help, variables, vectors, matrices, linear algebra, mathematical functions, plotting, selection programming, M-files, and user defined functions in MATLAB. The key topics covered include how to start MATLAB, the different display windows, assigning and working with variables, creating and manipulating vectors and matrices, and solving systems of linear equations using MATLAB.
This document provides an introduction and overview of MATLAB. It discusses what MATLAB is, the basic MATLAB interface and environment, variables and data types, basic math and logical operations, built-in functions, and some examples of basic MATLAB operations. MATLAB stands for Matrix Laboratory and is designed for matrix operations. It allows technical computing problems to be solved quickly using matrices and vectors. The MATLAB environment is command-based and results are displayed in the command window. Help is accessible through the help menu or typing help commands.
MATLAB is a matrix laboratory software package for numerical computation and visualization. It provides functions and tools for matrix manipulation, plotting and visualization, implementation of algorithms, data analysis, and numerical solution of problems. MATLAB has a programming language and interactive environment for algorithm development, data visualization, data analysis and numeric computation. It supports matrix and array operations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages.
MATLAB is a numerical computing environment and programming language. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, and interfacing with programs in other languages. MATLAB can be used for applications like signal processing, image processing, control systems, and computational finance. It offers advantages like ease of use, platform independence, and predefined functions. However, it can sometimes be slow and is commercial software. The MATLAB interface includes a command window, current directory, workspace, and command history. Arrays are fundamental data types in MATLAB and can be vectors, matrices, or multidimensional. Variables are used to store information in the workspace and can represent different data types. Common operations include arithmetic, functions, and following the
This document discusses matrices and arrays in MATLAB. It defines matrices and vectors, and notes that MATLAB treats all variables as matrices. It explains how to enter matrices in MATLAB by listing elements separated by commas and semicolons. It also discusses built-in functions to generate matrices filled with zeros, ones, random values, or an identity matrix. The document covers operations on matrices like addition, subtraction, and multiplication. It explains how to extract sub-matrices and elements using indexing and introduces the colon operator.
This document provides an overview of MATLAB including its history, applications, development environment, built-in functions, and toolboxes. MATLAB stands for Matrix Laboratory and was originally developed in the 1970s at the University of New Mexico to provide an interactive environment for matrix computations. It has since grown to be a comprehensive programming language and environment used widely in technical computing across many domains including engineering, science, and finance. The key components of MATLAB are its development environment, mathematical function library, programming language, graphics capabilities, and application programming interface. It also includes a variety of toolboxes that provide domain-specific functionality in areas like signal processing, neural networks, and optimization.
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
This document provides an introduction and overview of Matlab. It outlines the main Matlab screen components, discusses variables, arrays, matrices and indexing. It also covers basic operators, plotting functions, flow control, using M-files and writing user-defined functions. The key topics covered in 3 sentences or less are: Matlab allows matrix operations and plotting, has variables without types, and functions can be defined and saved in M-files to be called from the command window or other code.
This document provides an introduction and overview of MATLAB. It discusses the MATLAB environment, how to get help, variables, vectors, matrices, linear algebra, mathematical functions, plotting, selection programming, M-files, and user defined functions in MATLAB. The key topics covered include how to start MATLAB, the different display windows, assigning and working with variables, creating and manipulating vectors and matrices, and solving systems of linear equations using MATLAB.
This document provides an introduction and overview of MATLAB. It discusses what MATLAB is, the basic MATLAB interface and environment, variables and data types, basic math and logical operations, built-in functions, and some examples of basic MATLAB operations. MATLAB stands for Matrix Laboratory and is designed for matrix operations. It allows technical computing problems to be solved quickly using matrices and vectors. The MATLAB environment is command-based and results are displayed in the command window. Help is accessible through the help menu or typing help commands.
MATLAB is a matrix laboratory software package for numerical computation and visualization. It provides functions and tools for matrix manipulation, plotting and visualization, implementation of algorithms, data analysis, and numerical solution of problems. MATLAB has a programming language and interactive environment for algorithm development, data visualization, data analysis and numeric computation. It supports matrix and array operations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages.
MATLAB is a numerical computing environment and programming language. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, and interfacing with programs in other languages. MATLAB can be used for applications like signal processing, image processing, control systems, and computational finance. It offers advantages like ease of use, platform independence, and predefined functions. However, it can sometimes be slow and is commercial software. The MATLAB interface includes a command window, current directory, workspace, and command history. Arrays are fundamental data types in MATLAB and can be vectors, matrices, or multidimensional. Variables are used to store information in the workspace and can represent different data types. Common operations include arithmetic, functions, and following the
This document discusses matrices and arrays in MATLAB. It defines matrices and vectors, and notes that MATLAB treats all variables as matrices. It explains how to enter matrices in MATLAB by listing elements separated by commas and semicolons. It also discusses built-in functions to generate matrices filled with zeros, ones, random values, or an identity matrix. The document covers operations on matrices like addition, subtraction, and multiplication. It explains how to extract sub-matrices and elements using indexing and introduces the colon operator.
This document provides an overview of MATLAB including its history, applications, development environment, built-in functions, and toolboxes. MATLAB stands for Matrix Laboratory and was originally developed in the 1970s at the University of New Mexico to provide an interactive environment for matrix computations. It has since grown to be a comprehensive programming language and environment used widely in technical computing across many domains including engineering, science, and finance. The key components of MATLAB are its development environment, mathematical function library, programming language, graphics capabilities, and application programming interface. It also includes a variety of toolboxes that provide domain-specific functionality in areas like signal processing, neural networks, and optimization.
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
This document provides an introduction and overview of Matlab. It outlines the main Matlab screen components, discusses variables, arrays, matrices and indexing. It also covers basic operators, plotting functions, flow control, using M-files and writing user-defined functions. The key topics covered in 3 sentences or less are: Matlab allows matrix operations and plotting, has variables without types, and functions can be defined and saved in M-files to be called from the command window or other code.
Here are the key points about scalar-matrix addition in MATLAB:
- a is a scalar (single value)
- b is a matrix (2D array)
- To add a scalar to a matrix, MATLAB adds the scalar to each element of the matrix
- c = b + a performs element-wise addition, adding the value of a (which is 3) to each element of b
- The result c is the matrix b with 3 added to each element
So c would be:
c =
4 5 6
7 8 9
Scalar-matrix operations in MATLAB perform the operation on each element of the matrix.
This document provides an introduction to MATLAB. It discusses that MATLAB is a high-level language for technical computing where everything is a matrix and it is easy to perform linear algebra. It describes the MATLAB desktop interface and valid variable names. It also summarizes how to perform basic operations like addition, subtraction, multiplication, etc. on matrices and vectors. Finally, it outlines various matrix operations, statistical functions, random number generation, and plotting in MATLAB.
This document discusses MATLAB control structures for flow of execution including if/else statements, while loops, and for loops. It provides examples of basic syntax and use cases for each structure. Key points covered include evaluating conditional expressions, updating loop variables, and using for loops to iterate over array elements or ranges of indices.
Matlab is a high-level programming language and environment used for numerical computation, visualization, and programming. The document outlines key Matlab concepts including the Matlab screen, variables, arrays, matrices, operators, plotting, flow control, m-files, and user-defined functions. Matlab allows users to analyze data, develop algorithms, and create models and applications.
This document provides an overview of MATLAB and the Signal Processing Toolbox. It discusses MATLAB basics like commands, functions, variables and matrices. It also introduces key signal processing concepts like representing signals, basic waveform generation, convolution, and filters. The Signal Processing Toolbox allows analyzing and processing signals and includes tools for digital filter design and implementation, spectral analysis, and filtering signals.
The document provides an introduction to MATLAB, describing the main environment components like the command window and workspace. It explains basic MATLAB functions and variables, arrays, control flow statements, M-files, and common plotting and data analysis tools. Examples are given of different array operations, control structures, and building simple MATLAB functions and scripts.
This document provides an overview of MATLAB for geoscientists. It describes MATLAB as a high-level language and interactive environment for numerical computation, visualization, and programming. Key features of MATLAB include its high-level language for numerical analysis, interactive environment, built-in mathematical functions, graphics for data visualization, and tools for algorithm and application development. The document discusses matrices, variables, basic arithmetic and programming in MATLAB, and provides examples of using MATLAB for tasks like plotting functions, solving equations, and working with arrays.
This document discusses the importance and advantages of MATLAB. It notes that MATLAB has matrices as its basic data element, supports vectorized operations, and has built-in graphical and statistical functions. Toolboxes can further expand MATLAB's functionality. While it uses more memory and CPU time than other languages, MATLAB allows both command line and programming capabilities. The document provides examples of how to create matrices, perform operations on matrices using functions like sum(), transpose(), and indexing. It also discusses matrix multiplication and how operations depend on matrix dimensions.
Introduction to Matlab
Lecture 1:
Introduction: What is Matlab, History of Matlab, strengths, weakness
Getting familiar with the interface: Layout, Pull down menus
Creating and manipulating objects: Variables (scalars, vectors, matrices, text strings), Operators (arithmetic, relational, logical) and built-in functions
This presentation provides an introduction to MATLAB. It discusses what MATLAB is, its advantages and disadvantages, typical uses, and how to start the MATLAB environment. It demonstrates basic MATLAB commands like plotting a sine wave and performing calculations. It also covers different types of files used in MATLAB like M-files, MAT-files and MEX-files. The presentation shows how to address matrices, perform matrix operations, and use functions to build matrices. It encourages viewers to access the online MATLAB helpdesk for additional information and support.
This document discusses MATLAB and its capabilities for 3D plotting and visualization. MATLAB can create various 3D plot types like line plots, mesh plots, surface plots, and contour plots that are useful for visualizing 3D data and functions. It also describes how to generate 3D surface and contour plots by defining a function over a grid of x and y values and plotting the corresponding z values. Examples are provided to illustrate generating 3D surface and contour plots in MATLAB.
This document provides Newton's formula for forward difference interpolation and an example of using it to find the value of tan(0.12).
- Newton's formula uses forward difference interpolation to find the value of a polynomial of degree n that fits a set of (n+1) equally spaced (x,y) points.
- The coefficients of the polynomial are determined using forward differences of the y-values.
- In the example, the value of tan(0.12) is found by applying Newton's formula to a table of tan(x) values from 0.10 to 0.30 using forward differences up to degree 4.
The document provides an introduction to MATLAB and Simulink. It describes MATLAB as a numerical computing environment and matrix laboratory that is used for data analysis, algorithm development, modeling, and more across many disciplines. Simulink is introduced as a block diagram environment for multi-domain simulation and model-based design. Key features and uses of MATLAB and Simulink are outlined, including acquiring and analyzing data, developing functions and algorithms, modeling and simulation.
This document provides an introduction to linear transformations. It defines a linear transformation as a function that maps one vector space to another while preserving vector addition and scalar multiplication. Key concepts discussed include the domain, co-domain, range, and pre-image of a linear transformation. Examples are given to demonstrate linear transformations and functions that are not linear transformations. The relationship between linear transformations and matrices is also explained.
This document discusses Riemann sums and the definite integral. It explains that the definite integral is defined as the limit of Riemann sums as the size of the subintervals approaches zero. It provides examples of calculating Riemann sums and shows how the definite integral can be approximated by Riemann sums. The document also outlines some key properties of the definite integral, such as how to integrate sums and how the integral relates to calculating the area under a curve.
This document provides an overview of data types and operators in MATLAB. It discusses the main data types including matrices, vectors, strings, structures, cell arrays, and numeric precision. It describes how to create and manipulate different data types using vectors, indexing, and the colon operator. The document also covers common operators for arithmetic, relational, logical, and bitwise operations. Structures are highlighted as useful for passing arguments to functions or making code robust against changes.
This document discusses eigenvalues and eigenvectors. It introduces eigenvalues and eigenvectors and some of their applications in areas like engineering, science, control theory and physics. It defines diagonal matrices and explains how eigenvalues and eigenvectors are used to transform a given matrix into a diagonal matrix. It also discusses how this process can be used to solve coupled differential equations. It provides background on linear independence and explains that the eigenvectors of a matrix must be linearly independent for diagonalization.
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptxanaveenkumar4
The MathWorks Certified MATLAB Associate (MCMA) exam is indeed 50 multiple choice questions. The time limit and passing score vary among the instances of the exam. (This difference corrects for exam instances that are easier or harder than the others, and helps to maintain a consistent standard for the credential.) At this level you can expect to complete the entire process (sign-in, instructions, exam, sign-out) in under three hours.Identify the core components of the MATLAB desktop environment and explain their purpose
• Interactively import data into the MATLAB environment
• Examine data variables using the Variable Editor
• Create and customize data plots using Plot Tools
• Save and load MATLAB variables to and from disk interactively
This document provides an introduction and overview of MATLAB. It discusses what MATLAB is, its main features and interfaces. Some key points covered include:
- MATLAB is a computing environment for doing matrix manipulations, calculations and data analysis. It has specialized toolboxes for tasks like signal processing and system analysis.
- The main interfaces are the command window, workspace, command history and editor window. Commands can be executed directly, through script files or custom functions.
- MATLAB handles matrices and vectors natively and has extensive math and graphics functions. Basic operations include matrix/vector creation, arithmetic, plotting and flow control structures.
- Help is available through the help menu, demos and documentation. Common functions covered
Here are the key points about scalar-matrix addition in MATLAB:
- a is a scalar (single value)
- b is a matrix (2D array)
- To add a scalar to a matrix, MATLAB adds the scalar to each element of the matrix
- c = b + a performs element-wise addition, adding the value of a (which is 3) to each element of b
- The result c is the matrix b with 3 added to each element
So c would be:
c =
4 5 6
7 8 9
Scalar-matrix operations in MATLAB perform the operation on each element of the matrix.
This document provides an introduction to MATLAB. It discusses that MATLAB is a high-level language for technical computing where everything is a matrix and it is easy to perform linear algebra. It describes the MATLAB desktop interface and valid variable names. It also summarizes how to perform basic operations like addition, subtraction, multiplication, etc. on matrices and vectors. Finally, it outlines various matrix operations, statistical functions, random number generation, and plotting in MATLAB.
This document discusses MATLAB control structures for flow of execution including if/else statements, while loops, and for loops. It provides examples of basic syntax and use cases for each structure. Key points covered include evaluating conditional expressions, updating loop variables, and using for loops to iterate over array elements or ranges of indices.
Matlab is a high-level programming language and environment used for numerical computation, visualization, and programming. The document outlines key Matlab concepts including the Matlab screen, variables, arrays, matrices, operators, plotting, flow control, m-files, and user-defined functions. Matlab allows users to analyze data, develop algorithms, and create models and applications.
This document provides an overview of MATLAB and the Signal Processing Toolbox. It discusses MATLAB basics like commands, functions, variables and matrices. It also introduces key signal processing concepts like representing signals, basic waveform generation, convolution, and filters. The Signal Processing Toolbox allows analyzing and processing signals and includes tools for digital filter design and implementation, spectral analysis, and filtering signals.
The document provides an introduction to MATLAB, describing the main environment components like the command window and workspace. It explains basic MATLAB functions and variables, arrays, control flow statements, M-files, and common plotting and data analysis tools. Examples are given of different array operations, control structures, and building simple MATLAB functions and scripts.
This document provides an overview of MATLAB for geoscientists. It describes MATLAB as a high-level language and interactive environment for numerical computation, visualization, and programming. Key features of MATLAB include its high-level language for numerical analysis, interactive environment, built-in mathematical functions, graphics for data visualization, and tools for algorithm and application development. The document discusses matrices, variables, basic arithmetic and programming in MATLAB, and provides examples of using MATLAB for tasks like plotting functions, solving equations, and working with arrays.
This document discusses the importance and advantages of MATLAB. It notes that MATLAB has matrices as its basic data element, supports vectorized operations, and has built-in graphical and statistical functions. Toolboxes can further expand MATLAB's functionality. While it uses more memory and CPU time than other languages, MATLAB allows both command line and programming capabilities. The document provides examples of how to create matrices, perform operations on matrices using functions like sum(), transpose(), and indexing. It also discusses matrix multiplication and how operations depend on matrix dimensions.
Introduction to Matlab
Lecture 1:
Introduction: What is Matlab, History of Matlab, strengths, weakness
Getting familiar with the interface: Layout, Pull down menus
Creating and manipulating objects: Variables (scalars, vectors, matrices, text strings), Operators (arithmetic, relational, logical) and built-in functions
This presentation provides an introduction to MATLAB. It discusses what MATLAB is, its advantages and disadvantages, typical uses, and how to start the MATLAB environment. It demonstrates basic MATLAB commands like plotting a sine wave and performing calculations. It also covers different types of files used in MATLAB like M-files, MAT-files and MEX-files. The presentation shows how to address matrices, perform matrix operations, and use functions to build matrices. It encourages viewers to access the online MATLAB helpdesk for additional information and support.
This document discusses MATLAB and its capabilities for 3D plotting and visualization. MATLAB can create various 3D plot types like line plots, mesh plots, surface plots, and contour plots that are useful for visualizing 3D data and functions. It also describes how to generate 3D surface and contour plots by defining a function over a grid of x and y values and plotting the corresponding z values. Examples are provided to illustrate generating 3D surface and contour plots in MATLAB.
This document provides Newton's formula for forward difference interpolation and an example of using it to find the value of tan(0.12).
- Newton's formula uses forward difference interpolation to find the value of a polynomial of degree n that fits a set of (n+1) equally spaced (x,y) points.
- The coefficients of the polynomial are determined using forward differences of the y-values.
- In the example, the value of tan(0.12) is found by applying Newton's formula to a table of tan(x) values from 0.10 to 0.30 using forward differences up to degree 4.
The document provides an introduction to MATLAB and Simulink. It describes MATLAB as a numerical computing environment and matrix laboratory that is used for data analysis, algorithm development, modeling, and more across many disciplines. Simulink is introduced as a block diagram environment for multi-domain simulation and model-based design. Key features and uses of MATLAB and Simulink are outlined, including acquiring and analyzing data, developing functions and algorithms, modeling and simulation.
This document provides an introduction to linear transformations. It defines a linear transformation as a function that maps one vector space to another while preserving vector addition and scalar multiplication. Key concepts discussed include the domain, co-domain, range, and pre-image of a linear transformation. Examples are given to demonstrate linear transformations and functions that are not linear transformations. The relationship between linear transformations and matrices is also explained.
This document discusses Riemann sums and the definite integral. It explains that the definite integral is defined as the limit of Riemann sums as the size of the subintervals approaches zero. It provides examples of calculating Riemann sums and shows how the definite integral can be approximated by Riemann sums. The document also outlines some key properties of the definite integral, such as how to integrate sums and how the integral relates to calculating the area under a curve.
This document provides an overview of data types and operators in MATLAB. It discusses the main data types including matrices, vectors, strings, structures, cell arrays, and numeric precision. It describes how to create and manipulate different data types using vectors, indexing, and the colon operator. The document also covers common operators for arithmetic, relational, logical, and bitwise operations. Structures are highlighted as useful for passing arguments to functions or making code robust against changes.
This document discusses eigenvalues and eigenvectors. It introduces eigenvalues and eigenvectors and some of their applications in areas like engineering, science, control theory and physics. It defines diagonal matrices and explains how eigenvalues and eigenvectors are used to transform a given matrix into a diagonal matrix. It also discusses how this process can be used to solve coupled differential equations. It provides background on linear independence and explains that the eigenvectors of a matrix must be linearly independent for diagonalization.
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptxanaveenkumar4
The MathWorks Certified MATLAB Associate (MCMA) exam is indeed 50 multiple choice questions. The time limit and passing score vary among the instances of the exam. (This difference corrects for exam instances that are easier or harder than the others, and helps to maintain a consistent standard for the credential.) At this level you can expect to complete the entire process (sign-in, instructions, exam, sign-out) in under three hours.Identify the core components of the MATLAB desktop environment and explain their purpose
• Interactively import data into the MATLAB environment
• Examine data variables using the Variable Editor
• Create and customize data plots using Plot Tools
• Save and load MATLAB variables to and from disk interactively
This document provides an introduction and overview of MATLAB. It discusses what MATLAB is, its main features and interfaces. Some key points covered include:
- MATLAB is a computing environment for doing matrix manipulations, calculations and data analysis. It has specialized toolboxes for tasks like signal processing and system analysis.
- The main interfaces are the command window, workspace, command history and editor window. Commands can be executed directly, through script files or custom functions.
- MATLAB handles matrices and vectors natively and has extensive math and graphics functions. Basic operations include matrix/vector creation, arithmetic, plotting and flow control structures.
- Help is available through the help menu, demos and documentation. Common functions covered
This document provides an overview of MATLAB, its applications, and how to use its features. MATLAB can be used for numerical computation and was originally designed for matrix operations. It has since expanded to include tools for data analysis, signal processing, optimization, and more. The document describes MATLAB's basic interface and commands, how to work with matrices and vectors, perform math operations and logical operations, plot functions, write M-files and functions, and save and load work. It also briefly mentions Simulink for modeling and simulating dynamic systems.
This document provides an introduction to MATLAB. It begins with an overview of the MATLAB environment and display windows. It then discusses getting help in MATLAB, variables, vectors, matrices, linear algebra, plotting, built-in functions, selection programming using if/else statements, M-files, user-defined functions, and specific topics. Key points covered include the MATLAB interface, basic programming constructs like variables and arrays, and tools for computation, visualization, and programming in MATLAB.
This document provides an introduction and overview of MATLAB. It discusses MATLAB basics like the command window and variables. It also covers topics like working with matrices, vectors, plotting, scripts and functions. Specific MATLAB commands covered include plot, mesh, surf, contour and more. Functions like length, dot, cross and special matrices like ones, zeros and eye are also explained.
This document provides an overview of key concepts for working with numerical analysis in MATLAB, including:
1) Rules for selecting variable names in MATLAB, which must start with a letter and be 31 characters or less, and some forbidden names like "a*b" which signifies multiplication.
2) Case sensitivity of variable names and best practices for using meaningful names.
3) How MATLAB evaluates expressions and calculates mathematical functions like trigonometric, exponential, rounding, and other functions.
4) Formatting of numbers in MATLAB and how to construct and manipulate vectors using colon notation and dot arithmetic operations.
This document discusses MATLAB and provides examples of generating common discrete time signals such as unit impulse, unit step, ramp, exponential and sawtooth signals. MATLAB is an interpreted language well-suited for matrix manipulation and contains built-in functions. Typical uses include math, modelling, data analysis and visualization. Scripts allow executing a series of commands and signals can be plotted versus time or index.
This document provides a summary of a course on introduction to MATLAB. The course includes 7 lectures covering topics like variables, operations, plotting, visualization, programming, solving equations and advanced methods. It will have problem sets to be submitted after each lecture and requirements to pass include attending all lectures and completing all problem sets. The course materials provide an overview of MATLAB including getting started, creating and manipulating variables, and basic plotting.
This document provides an overview of MATLAB, including its uses, features, and basic programming concepts. MATLAB is a numerical computing environment and programming language that allows matrix manipulations, data visualization, algorithm development, and interfacing with other languages. It has a comprehensive set of built-in functions for mathematical and technical computing. The document discusses MATLAB's programming constructs like scripts, functions, operators, decision making statements, and loops. It also covers basic data types like vectors and matrices.
This document provides an overview of variables, arrays, and other basic programming concepts in MATLAB. It discusses how variables store and retrieve values, how arrays can have multiple dimensions and elements can be accessed using indexing, and how basic operations can be performed on arrays element-wise or across entire arrays using functions. Various functions for creating arrays filled with zeros, ones, or random values are also introduced.
This document provides an overview of key concepts in MATLAB including:
- MATLAB can be used as a powerful calculator or programming language. It has many built-in functions and the ability to define variables and scripts.
- Scripts allow storing and running sequences of MATLAB commands. Variables can be created and manipulated using basic arithmetic, element-wise, and matrix operations.
- Common variable types include numeric arrays and cell arrays. Variables are initialized without declaring type or size. Built-in functions help work with variables.
- Key concepts covered include scripts, variables, vectors, matrices, basic operations, and plotting. Examples are provided to demonstrate MATLAB basics.
This chapter discusses mathematical operations with arrays in MATLAB. It covers topics such as addition, subtraction, multiplication, and division of arrays. Array operations can be performed elementwise or using matrix multiplication. Built-in functions like mean, max, and sort can be used to analyze array properties. Random number generation functions rand, randn and randi are also introduced.
Introduction to programming in MATLAB
Youtube: https://www.youtube.com/watch?v=gDhpqj13dTA
Github: https://github.com/Mustafa-nafaa/Multimedia-TechnologyLab/tree/main/Week1:Introduction%20Matlab
This document provides an introduction to MATLAB, covering topics such as its command-oriented interface, variable names, matrices, plotting, logical and relational operators, and toolboxes. MATLAB was originally designed for solving linear algebra problems using matrices and treats all variables as matrices. It allows importing/exporting data and contains toolboxes for tasks like signal processing, control systems, statistics and more.
An Introduction to MATLAB for beginnersMurshida ck
This document provides an introduction to MATLAB, including:
- MATLAB is a program for numerical computation, originally designed for matrix operations. It has expanded capabilities for data analysis, signal processing, and other scientific tasks.
- The MATLAB desktop includes tools like the Command Window, Workspace, and Figure Window. Common commands are introduced for arithmetic, variables, arrays, strings and plots.
- Arrays in MATLAB can represent vectors and matrices. Commands are demonstrated for creating, manipulating, and performing operations on arrays.
This document provides an introduction and overview of MATLAB. It discusses the MATLAB desktop interface including the command window, command history, workspace browser, and start menu. It then covers MATLAB fundamentals such as entering expressions and variables, basic math operations, and how to enter vectors and matrices. Key MATLAB commands and functions are also introduced.
MATLAB is a high-level programming language and computing environment used for numerical computations, visualization, and programming. The document discusses MATLAB's capabilities including its toolboxes, plotting functions, control structures, M-files, and user-defined functions. MATLAB is useful for engineering and scientific calculations due to its matrix-based operations and built-in functions.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
The CBC machine is a common diagnostic tool used by doctors to measure a patient's red blood cell count, white blood cell count and platelet count. The machine uses a small sample of the patient's blood, which is then placed into special tubes and analyzed. The results of the analysis are then displayed on a screen for the doctor to review. The CBC machine is an important tool for diagnosing various conditions, such as anemia, infection and leukemia. It can also help to monitor a patient's response to treatment.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
Discover the latest insights on Data Driven Maintenance with our comprehensive webinar presentation. Learn about traditional maintenance challenges, the right approach to utilizing data, and the benefits of adopting a Data Driven Maintenance strategy. Explore real-world examples, industry best practices, and innovative solutions like FMECA and the D3M model. This presentation, led by expert Jules Oudmans, is essential for asset owners looking to optimize their maintenance processes and leverage digital technologies for improved efficiency and performance. Download now to stay ahead in the evolving maintenance landscape.
artificial intelligence and data science contents.pptxGauravCar
What is artificial intelligence? Artificial intelligence is the ability of a computer or computer-controlled robot to perform tasks that are commonly associated with the intellectual processes characteristic of humans, such as the ability to reason.
› ...
Artificial intelligence (AI) | Definitio
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
3. Desktop Basics
• When you start MATLAB, the desktop appears in its default layout.
• The desktop includes these panels:
• Current Folder — Access your files.
• Command Window — Enter commands at the command line,
indicated by the prompt (>>).
• Workspace — Explore data that you create or import from files.
• Command History — View or rerun commands that you entered
at the command line.
4.
5. Command Window
• As you work in MATLAB, you issue commands that create variables and call functions.
• For example, create a variable named a by typing this statement at the command line:
• a = 1
• MATLAB adds variable a to the workspace and displays the result in the Command
Window.
• a =
1
• Create a few more variables.
• b = 2
b =
2
• c = a + b
c =
3
• d = cos(a)
d =
0.5403
6. • When you do not specify an output variable, MATLAB uses the
variable ans, short for answer, to store the results of your calculation.
• sin(a)
ans =
0.8415
• If you end a statement with a semicolon, MATLAB performs the
computation, but suppresses the display of output in the Command
Window.
• e = a*b;
7. Numbers and arithmetic operations
• There are 3 kinds of numbers used in MATLAB:
integers
real numbers
complex numbers
• Integers are entered without the decimal point.
• xi = 10
xi =
10
• Real numbers are entered with the decimal point.
• xr = 10.01
xi =
10.0100
8. • Variables realmin and realmax denote the smallest and the largest
positive real numbers in MATLAB. For instance,
• Realmin
ans =
2.2251e-308
9. Complex Numbers
• Complex numbers have both real and imaginary parts, where the imaginary
unit is the square root of –1.
• sqrt(-1)
ans =
0 + 1.0000i
• To represent the imaginary part of complex numbers, use either i or j.
• i
ans =
0 + 1.0000i
• c = [3+4i, 4+3j, -i, 10j]
• c =
3.0000+4.0000i 4.0000+3.0000i 0-1.0000i 0+10.0000i
10. • In addition to classes of numbers mentioned above, MATLAB has three
variables representing the non-numbers:
• -Inf
• Inf
• NaN
• The –Inf and Inf are the IEEE representations for the negative and positive
infinity, respectively.
• Infinity is generated by overflow or by the operation of dividing by zero.
• The NaN standsfor the not-a-numberand is obtained as a result of the
mathematicallyundefined operations such as
0.0/0.0 or ∞-∞
.
11. Numbers and arithmetic operations….
Operation Symbol
addition +
subtraction -
multiplication *
division / or
exponentiation ^
13. WorkspaceVariables
• The workspace contains variables that you create within or import
into MATLAB from data files or other programs. For example, these
statements create variables A and B in the workspace.
• A = magic(4);
• B = rand(3,5,2);
• You can view the contents of the workspace using whos.
• whos
• Name Size Bytes Class
A 4x4 128 double
B 3x5x2 240 double
14. • The variables also appear in the Workspace pane on the desktop.
• Workspace variables do not persist after you exit MATLAB. Save your
data for later use with the save command,
save myfile.mat
• Saving preserves the workspace in your current working folder in a
compressed file with a .mat extension, called a MAT-file.
• To clear all the variables from the workspace, use the clear command.
• Restore data from a MAT-file into the workspace using load.
load myfile.mat
15. • To save your current workspace select Save Workspace as… from the
File menu.
• Another way of saving your workspace is to type save filename in the
Command Window. The following command save filename s saves
only the variable s.
• Another way to save your workspace is to type the command diary
filename in the Command Window. All commands and variables
created from now will be saved in your file. The following command:
diary off will close the file and save it as the text file.
• To load contents of the file named filename into MATLAB's workspace
type load filename in the Command Window.
16. Suppressing Output
• If you simply type a statement and press Return or Enter, MATLAB
automatically displays the results on screen.
• However, if you end the line with a semicolon, MATLAB performs the
computation, but does not display any output. This is particularly
useful when you generate large matrices.
• For example,
• A = magic(100);
17. Entering Long Statements
• If a statement does not fit on one line, use an ellipsis (three periods),
..., followed by Return or Enter to indicate that the statement
continues on the next line. For example,
• s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
• Blank spaces around the =, +, and - signs are optional, but they
improve readability.
18.
19. Matrices and Arrays
• MATLAB is an abbreviation for "matrix laboratory. "While other
programming languages mostly work with numbers one at a time,
MATLAB is designed to ,operate primarily on whole matrices and
arrays.
• All MATLAB variables are multidimensional arrays, no matter what
type of data. A matrix is a two-dimensional array often used for linear
algebra.
20. Array Creation
• To create an array with four elements in a single row, separate the
elements with either a comma (,) or a space.
• a = [1 2 3 4]
returns
• a =
1 2 3 4
• This type of array is a row vector.
• To create a matrix that has multiple rows, separate the rows with
semicolons.
• a = [1 2 3; 4 5 6; 7 8 10]
• a =
1 2 3
4 5 6
7 8 10
21. • Another way to create a matrix is to use a function, such as ones,
zeros, or rand. For example, create a 5-by-1 column vector of zeros.
• z = zeros(5,1)
• z =
0
0
0
0
0
22. Matrix and Array Operations
• MATLAB allows you to process all of the values in a matrix using a
single arithmetic operator or function.
• a + 10
• ans =
11 12 13
14 15 16
17 18 20
• sin(a)
• ans =
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
23. • To transpose a matrix, use a single quote ('):
• a'
• ans =
1 4 7
2 5 8
3 6 10
• You can perform standard matrix multiplication, which computes the inner
products between rows and columns, using the * operator. For example,
confirm that a matrix times its inverse returns the identity matrix:
• p = a*inv(a)
• p =
1.0000 0 -0.0000
0 1.0000 0
0 0 1.0000
• Notice that p is not a matrix of integer values.
24. • MATLAB stores numbers as floating-point values, and arithmetic operations
are sensitive to small differences between the actual value and its floating-
point representation.
• You can display more decimal digits using the format command:
• format long
p = a*inv(a)
• p =
1.000000000000000 0 -0.000000000000000
0 1.000000000000000 0
0 0 0.999999999999998
• Reset the display to the shorter format using
• format short
• format affects only the display of numbers, not the way MATLAB computes or
saves them.
25. • To perform element-wise multiplication rather than matrix multiplication
use the .* operator:
• p = a.*a
• p =
1 4 9
16 25 36
49 64 100
• The matrix operators for multiplication, division, and power each have a
corresponding array operator that operates element-wise. For example,
raise each element of a to the third power:
• a.^3
• ans =
1 8 27
64 125 216
343 512 1000
26. Concatenation
• Concatenation is the process of joining arrays to make larger ones. In
fact, you made your first array by concatenating its individual
elements.
• The pair, of square brackets [] is the concatenation operator.
• A = [a,a]
• A =
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
27. • Concatenating arrays next to one another using commas is called
horizontal concatenation. Each array must have the same number of
rows. Similarly, when the arrays have the same number of columns,
you can concatenate vertically using semicolons.
• A = [a; a]
• A =
1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
28. Array Indexing
• Every variable in MATLAB is an array that can hold many numbers.
When you want to access selected elements of an array, use indexing.
• For example, consider the 4-by-4 magic square A:
• A = magic(4)
• A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
29. • There are two ways to refer to a particular element in an array. The
most common way is to specify row and column subscripts, such as
• A(4 , 2)
• ans =
14
• Less common, but sometimes useful, is to use a single subscript that
traverses down each column in order:
• A(8)
• ans =
14
• Using a single subscript to refer to a particular element in an array is
called linear indexing.
30. • If you try to refer to elements outside an array on the right side of an
assignment statement, MATLAB throws an error.
• test = A(4,5)
• Attempted to access A(4,5); index out of bounds because size(A) =
[4,4].
• However, on the left side of an assignment statement, you can specify
elements outside the current dimensions. The size of the array
increases to accommodate the newcomers.
• A(4,5) = 17
• A =
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
31. • To refer to multiple elements of an array, use the colon operator, which
allows you to specify a range of the form start:end. For example, list the
elements in the first three rows and the second column of A:
• A(1:3,2)
• ans =
2
11
7
• The colon alone, without startor end values, specifies all of the elements
in that dimension. For example, select all the columns in the third row of A:
• A(3,:)
• ans =
9 7 6 12 0
32. • The colon operator also allows you to create an equally spaced vector
of values using the more general form start:step:end.
• B = 0:10:100
• B =
0 10 20 30 40 50 60 70 80 90 100
• If you omit the middle step, as in start:end, MATLAB uses the default
step value of 1.
33. Character Strings
• A character string is a sequence of any number of characters enclosed in single
quotes. You can assign a string to a variable.
• myText = 'Hello, world';
• If the text includes a single quote, use two single quotes within the definition.
• otherText = 'You''re right'
• otherText =
You're right
• myText and otherText are arrays, like all MATLAB variables. Their class or data
type is char, which is short for character.
• whos myText
• Name Size Bytes Class
myText 1x12 24 char
34. • You can concatenate strings with square brackets, just as you
concatenate numeric arrays.
• longText = [myText,' - ',otherText]
• longText =
Hello, world - You're right
• To convert numeric values to strings, use functions, such as num2str
or int2str.
• f = 71;
c = (f-32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']k
• tempText =
Temperature is 21.6667C
35. Sum, Transpose, and diag
• A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
• MATLAB displays the matrix you just entered:
• A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
• The special properties of a magic square have to do with the various
ways of summing its elements. If you take the sum along any row or
column, or along either of the two main diagonals, you will always get
the same number. Let us verify that using MATLAB.
36. • sum(A)
• ans =
34 34 34 34
• It has computed a row vector containing the sums of the columns of A.
• Each of the columns has the same sum, the magic sum, 34.
• How about the row sums? MATLAB has a preference for working with the
columns of a matrix, so one way to get the row sums is to transpose the
matrix, compute the column sums of the transpose, and then transpose
the result.
• (sum(A’))’
• ans =
34
34
34
34
37. • The sum of the elements on the main diagonal is obtained with the
sum and the diag functions:
• sum(diag(A))
• ans =
34
• The other diagonal, the so-called antidiagonal, is not so important
mathematically, so MATLAB does not have a ready-made function for
it. But a function originally intended for use in graphics, fliplr, flips a
matrix from left to right:
• sum(diag(fliplr(A)))
• ans =
34
38. • B = magic(4)
• B =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
• If it is required to swap the two rows or columns
• A = B(:,[1 3 2 4])
• This subscript indicates that—for each of the rows of matrix B—reorder the
elements in the order 1, 3, 2, 4. It produces:
• A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
39. Generating Matrices
• Z = zeros(2,4)
• Z =
0 0 0 0
0 0 0 0
• F = ones(3,3)
• F =
1 1 1
1 1 1
1 1 1
• N = rand(1,10)
• N = fix(N)
40. Variables
• Like most other programming languages, the MATLAB language provides
mathematicalexpressions,but unlike most programming languages, these
expressions involve entire matrices
• MATLAB does not require any type declarations or dimension statements.
• When MATLAB encounters a new variable name, it automaticallycreates
the variable and allocates the appropriate amount of storage. If the
variable already exists, MATLAB changes its contents and, if necessary,
allocates new storage.
• For example, num_students = 25, creates a 1-by-1 matrix named
num_students and stores the value 25 in its single element.
• To view the matrix assigned to any variable, simply enter the variable
name.
41. • Variable names consist of a letter, followed by any number of letters,
digits, or underscores.
• MATLAB is case sensitive; it distinguishes between uppercase and
lowercase letters. A and a are not the same variable.
42. Numbers
• MATLAB uses conventional decimal notation, with an optional
decimal point and leading plus or minus sign, for numbers.
• Scientific notation uses the letter e to specify a power-of-ten scale
factor.
• Imaginary numbers use either i or j as a suffix.
• Some examples of legal numbers are
• 3 -99 0.0001
9.6397238 1.60210e-20 6.02252e23
1i -3.14159j 3e5i
43. Matrix Operators
• Expressions use familiar arithmetic operators and precedence rules.
• + Addition
• - Subtraction
• * Multiplication
• / Division
• Left division
• ^ Power
• ' Transpose
• ( ) Specify evaluation order
44. Array Operators
• When they are taken away from the world of linear algebra, matrices
become two-dimensional numeric arrays.
• Arithmetic operations on arrays are done element by element. This means
that addition and subtraction are the same for arrays and matrices,but
that multiplicativeoperations are different. MATLAB uses a dot, or decimal
point, as part of the notation for multiplicativearray operations.
• + Addition
• - Subtraction
• .* Element-by-element multiplication
• ./ Element-by-element division
• . Element-by-element left division
• .^ Element-by-element power
45. Building Tables
• Array operations are useful for building tables. Suppose n is the column vector
• n = (0:9)';
• pows = [n n.^2 2.^n]
builds a table of squares and powers of 2:
• pows =
0 0 1
1 1 2
2 4 4
3 9 8
4 16 16
5 25 32
6 36 64
7 49 128
8 64 256
9 81 512
46. Functions
• MATLAB provides a large number of standard elementary mathematical
functions, including abs, sqrt, exp, and sin.
• Taking the square root or logarithm of a negative number is not an error;
the appropriate complex result is produced automatically.
• MATLAB also provides many more advanced mathematicalfunctions,
including Bessel and gamma functions. Most of these functions accept
complex arguments. For a list of the elementary mathematical functions,
type
• help elfun
• For a list of more advanced mathematicaland matrix functions, type
help specfun
help elmat
47. • Some of the functions, like sqrt and sin, are built in.
• Built-in functions are part of the MATLAB core so they are very
efficient, but the computational details are not readily accessible.
• Other functions are implemented in the MATLAB programing
language, so their computational details are accessible.
• There are some differences between built-in functions and other
functions.
• For example, for built-in functions, you cannot see the code. For
other functions, you can see the code and even modify it if you want.
48. The format Function
• The format function controls the numeric format of the values displayed.
• The function affects only how numbers are displayed, not how MATLAB software
computes or saves them. Here are the different formats, together with the resulting
output produced from a vector x with components of different magnitudes.
• Syntax
format
format type
• x = [4/3 1.2345e-6]
• format short (Scaled fixed point format, with 5 digits)
1.3333 0.0000
• format short e (Floating point format, with 5 digits.)
1.3333e+000 1.2345e-006
• format short g (Best of fixed or floating point, with 5 digits.)
1.3333 1.2345e-006
• format short eng (Engineering format that has at least 5 digits and a power that is a
multiple of three)
1.3333e+000 1.2345e-006
49. • format long (Scaled fixed point format, with 15 digits)
1.33333333333333 0.00000123450000
• format long e
1.333333333333333e+000 1.234500000000000e-006
• format long g
1.33333333333333 1.2345e-006
• format bank
1.33 0.00
• format rat
4/3 1/810045
• format hex
3ff5555555555555 3eb4b6231abfd271
50. • If the largest element of a matrix is larger than 103 or smaller than
10-3, MATLAB applies a common scale factor for the short and long
formats.
• In addition to the format functions shown above
• format compact suppresses many of the blank lines that appear in the
output. This lets you view more information on a screen or window. If
you want more control over the output format, use the sprintf and
fprintf functions.
• format loose
• View the current format by typing
get(0,’format’)
51. Command Line Editing
• Various arrow and control keys on your keyboard allow you to recall, edit,
and reuse statementsyou have typed earlier.
• For example, suppose you mistakenly enter
• rho = (1 + sqt(5))/2
• You have misspelled sqrt. MATLAB responds with
• Undefined function 'sqt' for input arguments of type 'double'.
• Instead of retyping the entire line, simply press the ↑ key. The statement
you typed is redisplayed. Use the ← key to move the cursor over and insert
the missing r. Repeated use of the ↑ key recalls earlier lines. Typing a few
characters, and then pressing the ↑ key finds a previous line that begins
with those characters. You can also copy previously executed statements
from the Command History.
52. The m-files
• Files that contain a computer code are called the m-files.
• There are two kinds of m-files: the script files and the function files.
• Script files do not take the input arguments or return the output
arguments while The function files may take input arguments or return
output arguments.
• To create m-file click File -> New -> Script
• MATLAB Editor/Debugger screen is opened.
• Here we will type our code, can make changes, etc. Once we are
done with typing, click on File, in the MATLAB Editor/Debugger
screen and select Save As… .
53. The m-files…
• Chose a name for the file, e.g., filename.m and click on Save.
• Make sure that your file is saved in the directory that is in MATLAB's search
path.
• To open the m-file from within the Command Window type edit
filename and then press Enter or Return key.
• Example of Function of descending order.
54. Inline functions and the feval command
• Sometimes it is handy to define a function that will be used during the
current MATLAB session only.
• MATLAB has a command inline used to define the so-called inline functions
in the Command Window.
• f = inline('sqrt(x.^2+y.^2)','x','y')
f =
Inline function:
f(x,y) = sqrt(x.^2+y.^2)
55. Inline functions and the feval command…
• We can evaluate this function in a usual way
• f (3,4)
ans =
5
• This function also works with arrays.
• A = [1 2;3 4];
• B = ones(2);
• C = f(A, B)
C =
1.4142 2.2361
3.1623 4.1231
56. Inline functions and the feval command…
• Some functions take as the input argument a name of another function, which is
specified as a string.
• In order to execute function specified by string we use the command feval as shown
below
• feval('functname', input parameters of function functname)
57. Control flow
• To control the flow of commands, the makers of MATLAB supplied
four devices a programmer can use while writing his/her computer
code
• the for loops
• the while loops
• the if-else-end constructions
• the switch-case constructions
58. for loops
• Syntax of the for loop is shown below
for k = array
commands
end
• The commands between the for and end statements are executed for all
values stored in the array.
• Suppose that one-need values of the sine function at eleven evenly spaced
points πn/10, for n = 0, 1, …, 10. To generate the numbers in question one
can use the for loop
for n=0:10
x(n+1) = sin(pi*n/10);
end
59. for loops…
• The for loops can be nested
H = zeros(5);
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end
• H
H =
1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
60. for loops…
• The for loop should be used only when other methods cannot be applied.
Consider the following problem.
• Generate a 10-by-10 matrix A = [akl], where akl = sin(k)cos(l). Using nested
loops one can compute entries of the matrix A using the following code
A = zeros(10);
for k=1:10
for l=1:10
A(k,l) = sin(k)*cos(l);
end
end
61. for loops…
• A loop free version might look like this
k = 1:10;
A = sin(k)'*cos(k);
• First command generates a row array k consisting of integers 1, 2, … , 10.
• The command sin(k)‘ creates a column vector while cos(k) is the row
vector.
• Components of both vectors are the values of the two trig functions
evaluated at k.
• Code presented above illustrates a powerful feature of MATLAB called
vectorization. This technique should be used whenever it is possible.
62. while loops
• Syntax of the while loop is
while expression
statements
End
• This loop is used when the programmer does not know the number
of repetitions a priori.
• The number π is divided by 2. The resulting quotient is divided by 2
again. This process is continued till the current quotient is less than
or equal to 0.01. What is the largest quotient that is greater than
0.01 ?
q = pi;
while q > 0.01
q = q/2;
end
63. The if-else-endconstructions
• Syntax of the simplest form of the construction is
if expression
commands
End
• This construction is used if there is one alternative only.
• Two alternatives require the construction
if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end
64. The if-else-endconstructions…
• If there are several alternatives, we use the following construction
if expression1
commands (evaluated if expression 1 is true)
elseif expression 2
commands (evaluated if expression 2 is true)
elseif …
...
else
commands (executed if all previous expressions evaluate to false)
end
65. The if-else-endconstructions…
• Chebyshev polynomials Tn(x), n = 0, 1, … of the first kind are of great
importance in numerical analysis. They are defined recursively as follows
Tn(x) = 2xTn-1(x) – Tn-2(x), n = 2, 3, … , T0(x) = 1, T1(x) = x.
• Implementation of this definition is easy
66. The if-else-end constructions…
function T = ChebT(n)
% Coefficients T of the nth Chebyshev polynomial of the first kind. They are
stored in the descending order of powers.
t0 = 1;
t1 = [1 0];
if n == 0
T = t0;
elseif n == 1;
T = t1;
else
for k=2:n
T = [2*t 0] - [0 0 t0];
t0 = t1;
t1 = T;
end
end
68. The switch-case construction
• Syntax of the switch-case construction is
switch expression (scalar or string)
case value1 (executes if expression evaluates to value1)
commands
case value2 (executes if expression evaluates to value2)
commands
.
.
.
otherwise
statements
end
69. The switch-case construction…
• Switch compares the input expression to each case value. Once the match
is found it executes the associated commands.
• a random integer number x from the set {1, 2, … , 10} is generated. If x = 1
or x = 2, then the message Probability = 20% is displayed to the screen. If x
= 3 or 4 or 5, then the message Probability = 30% is displayed, otherwise
the message Probability = 50% is generated.
x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10}
switch x
case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%');
otherwise
disp('Probability = 50%');
end
70. The switch-case construction…
• Here are new MATLAB functions that are used in earlier code (file fswitch)
• rand – uniformly distributed random numbers in the interval (0, 1)
• ceil – round towards plus infinity infinity
• disp – display string/array to the screen
• Let us test this code ten times
for k = 1:10
fswitch
end
71. Relations and logical operators
• Comparisons in MATLAB are performed with the aid of the following operators
Operator Description
< Less than
<= Less than or equal to
> Greater
>= Greater or equal to
== Equal to
~= Not equal to
72. Relations and logical operators…
• Operator == compares two variables and returns ones when they are equal
and zeros otherwise.
• a= [1 1 3 4 1]
a =
1 1 3 4 1
• ind = (a == 1)
ind =
1 1 0 0 1
• b = a(ind)
b =
1 1 1
73. Relations and logical operators…
• We can obtain the same result using function find
ind = find(a == 1)
ind =
1 2 5
• Variable ind now holds indices of those entries that satisfy the imposed
condition. To extract all ones from the array a use
• b = a(ind)
b =
1 1 1
74. Relations and logical operators…
• There are three logical operators available in MATLAB
• If one wants to select all entries x that satisfy the inequalities x >=1
or x < -0.2
• x = randn(1,7)
x =
-0.4326 -1.6656 0.1253 0.2877 -1.1465 1.1909 1.1892
Operator Description
| And
& Or
~ Not
75. Relations and logical operators…
• ind = (x >= 1) | (x < -0.2)
ind =
1 1 0 0 1 1 1
• y = x(ind)
y =
-0.4326 -1.6656 -1.1465 1.1909 1.1892
• In addition to relational and logical operators MATLAB has several logical
functions designed for performing similar tasks. These functions return 1
(true) if a specific condition is satisfied and 0 (false) otherwise.
76. Relations and logical operators…
• isempty(y)
ans =
0
returns 0 because the array y of the last example is not empty.
• isempty([ ])
ans =
1
returns 1 because the argument of the function used is the empty array [ ].
77. Rounding to integers. Functions ceil, floor,
fix and round
Function Description
floor Round towards minus infinity
ceil Round towards plus infinity
fix Round towards zero
round Round towards nearest integer
78. Rounding to integers. Functions ceil,
floor, fix and round…
• To illustrate differences between these functions let us create first a two-
dimensional array of random numbers that are normally distributed (mean
= 0, variance = 1) using another MATLAB function randn
• randn('seed', 0) % This sets the seed of the random numbers generator
to zero
• T = randn(5)
• T =
1.1650 1.6961 -1.4462 -0.3600 -0.0449
0.6268 0.0591 -0.7012 -0.1356 -0.7989
0.0751 1.7971 1.2460 -1.3493 -0.7652
0.3516 0.2641 -0.6390 -1.2704 0.8617
-0.6965 0.8717 0.5774 0.9846 -0.0562
79. Rounding to integers. Functions ceil, floor, fix
and round…
• A = floor(T)
• B = ceil(T)
• C = fix(T)
• D = round(T)
• It is worth mentioning that the following identities
floor(x) = fix(x) for x > 0
ceil(x) = fix(x) for x < 0
hold true
• rep4.m
80. MATLAB graphics
• MATLAB has several high-level graphical routines. They allow a user
to create various graphical objects including two- and three-
dimensional graphs, graphical user interfaces (GUIs), movies, to
mention the most important ones.
81. 2-D graphics
• Basic function used to create 2-D graphs is the plot function. This function takes a
variable number of input arguments.
• Example: the graph of the rational function 𝑓 𝑥 =
𝑥
1+𝑥2, -2<x<2, will be ploted using a
variable number of points on the graph of f(x)
82. 2-D graphics…
• % Script file graph1.
for n=1:2:5
n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
plot(x,y,'r')
title(sprintf('Graph %g. Plot based upon n = %g points.' ...,
(n+1)/2, n10))
axis([-2,2,-.8,.8])
xlabel('x')
ylabel('y')
83. 2-D graphics…
• The loop for is executed three times. Therefore, three graphs of the same
function will be displayed in the Figure Window.
• A MATLAB function linspace(a, b, n) generates a one-dimensional array of
n evenly spaced numbers in the interval [a b].
• The y-ordinates of the points to be plotted are stored in the array y.
• Command plot is called with three arguments: two arrays holding the x-
and the y-coordinates and the string 'r', which describes the color (red) to
be used to paint a plotted curve.
• We should notice a difference between three graphs created by this file.
There is a significant difference between smoothness of graphs 1 and 3.
84. 2-D graphics…
• MATLAB has several colors you can use to plot graphs:
y yellow
M magenta
c cyan
r red
g green
b blue
w white
k black
85. 2-D graphics…
• Based on the visual observation we can say: "more points you supply
the smoother graph is generated by the function plot".
• Function title adds a descriptive information to the graphs generated
by this m-file and is followed by the command sprintf.
• sprintf takes here three arguments: the string and names of two
variables printed in the title of each graph.
• To specify format of printed numbers we use here the construction
%g, which is recommended for printing integers
86. 2-D graphics…
• The command axis tells MATLAB what the dimensions of the box
holding the plot are.
• To add more information to the graphs created here, we label the x-
and the y-axes using commands xlabel and the ylabel, respectively.
Each of these commands takes a string as the input argument.
• Function grid adds the grid lines to the graph.
• The last command used before the closing end is the pause
command.
• The command pause(n) holds on the current graph for n seconds
before continuing, where n can also be a fraction.
• If pause is called without the input argument, then the computer
waits to user response. For instance, pressing the Enter key will
resume execution of a program.
87. 2-D graphics…
• Function subplot is used to plot of several graphs in the same Figure
Window. Here is a slight modification of the m-file graph1
• Script file graph2
• The command subplot is called here with three arguments. The first
two tell MATLAB that a 2-by-2 array consisting of four plots will be
created. The third parameter is the running index telling MATLAB
which subplot is currently generated.
88. 2-D graphics…
• Using command plot we can display several curves in the same
Figure Window.
% Script file graph3.
% Graphs of two ellipses
% x(t) = 3 + 6cos(t), y(t) = -2 + 9sin(t)
% and
% x(t) = 7 + 2cos(t), y(t) = 8 + 6sin(t).
• There are several new MATLAB commandswhich are used in this file.
• They are used here to enhance the readability of the graph.
89. 2-D graphics…
• The command in line 6 begins with h1 = plot…
• Variable h1 holds an information about the graph we generate and is
called the handle graphics.
• Command set used in the next line allows a user to manipulate a
plot. Note that this command takes as the input parameter the
variable h1.
• We change thickness of the plotted curves from the default value to
a width of our choice, namely 1.25.
• In the next line we use command axis to customize plot.
• We chose option 'square' to force axes to have square dimensions.
Other available options are: 'equal', 'normal', 'ij', 'xy', and 'tight'.
90. 2-D graphics…
• If function axis is not used, then the circular curves are not
necessarily circular. To justify this let us plot a graph of the unit circle
of radius 1 with center at the origin
t = 0:pi/100:2*pi;
x = cos(t);
y = sin(t);
plot(x,y)
• Function get takes as the first input parameter a variable named gca
= get current axis.
• Variable h = get(gca, … ) is the graphics handle of this axis.
91. 2-D graphics…
• With the information stored in variable h, we change the font size
associated with the x-axis using the 'FontSize' string followed by a
size of the font we wish to use.
• Invoking function set in line 12, we will change the tick marks along
the x-axis using the 'XTick' string followed by the array describing
distribution of marks.
• We can also make changes in the title of the plot.
• It should be obvious from the short discussion presented here that
two MATLAB functions get and set are of great importance in
manipulating graphs.
92. 2-D graphics…
• MATLAB has several functions designed for plotting specialized 2-D
graphs.
• A partial list of these functions is included here fill, polar, bar, barh,
pie, hist, compass, errorbar, stem, and feather.
• In this example function fill is used to create a well-known object
n = -6:6;
x = sin(n*pi/6);
y = cos(n*pi/6);
fill(x, y, 'r')
axis('square')
title('Graph of the n-gone')
text(-0.45,0,'What is a name of this object?')
93. 2-D graphics…
• Function fill takes three input parameters - two arrays, named here x
and y. They hold the x- and y-coordinates of vertices of the polygon
to be filled. Third parameter is the user-selected color to be used to
paint the object.
• A new command that appears in this short code is the text
command. It is used to annotate a text. First two input parameters
specify text location. Third input parameter is a text, which will be
added to the plot.
94. 3-D Graphics
• MATLAB has several built-in functions for plotting three-dimensional
objects. Some of them are:
plot3 to plot curves in space
mesh mesh surfaces
surf surfaces
contour contour plots
• For any help type help graph3d in the Command Window
95. 3-D Graphics…
• Let r(t) = < t cos(t), t sin(t), t >, -10π < t > 10π, be the space curve.
We plot its graph over the indicated interval using function plot3
• Script file graph4
• Function plot3 takes three input parameters – arrays holding
coordinates of points on the curve to be plotted.
96. 3-D Graphics
• Function mesh is intended for plotting graphs of the 3-D mesh
surfaces.
• function meshgrid generates two two-dimensional arrays for 3-D
plots.
• Suppose that one wants to plot a mesh surface over the grid that is
defined as the Cartesian product of two sets
x = [0 1 2];
y = [10 12 14];
The meshgrid command applied to the arrays x and y creates two
matrices.
[xi, yi] = meshgrid(x,y)
97. 3-D Graphics…
• Note that the matrix xi contains replicated rows of the array x while
yi contains replicated columns of y.
• The z-values of a function to be plotted are computedfrom arrays xi
and yi.
• In this example we will plot the hyperbolic paraboloid z = y2 – x2
over the square –1 < x < 1, –1 < y < 1
x = -1:0.05:1;
y = x;
[xi, yi] = meshgrid(x,y);
zi = yi.^2 – xi.^2;
mesh(xi, yi, zi)
axis off
98. 3-D Graphics…
• Now to plot the graph of the mesh surface together with the
contour plot beneath the plotted surface use function meshc
meshc(xi, yi, zi)
axis off
99. 3-D Graphics…
• Function surf is used to visualize data as a shaded surface.
• Computer code in the m-file graph5 should help us to learn some
finer points of the 3-D graphics in MATLAB
• % Script file graph5.
• command surfc plots a surface together with the level lines beneath.
• Unlike the command surfc the command surf plots a surface only
without the level curves.
• Command colormap is used to paint the surface using a user-
supplied colors. If the command colormap is not added, MATLAB
uses default colors.
100. 3-D Graphics…
• Here is a list of color maps that are available in MATLAB
hsv - hue-saturation-value color map
hot - black-red-yellow-white color map
gray - linear gray-scale color map
bone - gray-scale with tinge of blue color map
copper - linear copper-tonecolor map
pink - pastel shades of pink color map
white - all white color map
flag - alternating red, white, blue, and black color map
lines - color map with the line colors
101. 3-D Graphics…
colorcube - enhanced color-cube color map
vga - windows colormap for 16 colors
jet - variant of HSV
prism - prism color map
cool - shades of cyan and magentacolor map
autumn - shades of red and yellow color map
spring - shades of magenta and yellow color map
winter - shades of blue and green color map
summer - shades of green and yellow color map
102. 3-D Graphics…
• Command shading (see line 7) controls the color shading used to
paint the surface. Command in question takes one argument.
shading flat sets the shading of the current graph to flat
shading interp sets the shading to interpolated
shading faceted sets the shading to faceted, which is the default.
• Command view (see line 8) is the 3-D graph viewpoint specification.
It takes a three-dimensional vector, which sets the view angle in
Cartesian coordinates.
103. 3-D Graphics…
• Command figure prompts MATLAB to create a new Figure Window
in which the level lines will be plotted.
• In order to enhance the graph, we use command contourf instead of
contour. The former plots filled contour lines while the latter
doesn't.
• On the same line we use command hold on to hold the current plot
and all axis properties so that subsequent graphing commands add
to the existing graph.
• First command on line 25 returns matrix c and graphics handle h that
are used as the input parameters for the function clabel, which adds
height labels to the current contourplot.
104. Animation
• In addition to static graphs one can put a sequence of graphs in motion.
• In other words, we can make a movie using MATLAB graphics tools.
• To learn how to create a movie, let us analyze the m-file firstmovie.
105. Animation…
• Script file firstmovie.
• Command moviein, on line 1, with an integral parameter, tells
MATLAB that a movie consistingof five frames is created in the body
of this file.
• Consecutive frames are generated inside the loop for.
• getframe command means each frame of the movie is stored in the
column of the matrix m.
• Command movie(m) tells MATLAB to play the movie just created and
saved in columns of the matrix m.
106. Command Sphere and Cylinder
• MATLAB has some functions for generating special surfaces. We will
be concerned mostly with two functions- sphere and cylinder.
• The command sphere(n) generates a unit sphere with center at the
origin using (n+1)2 points.
• If function sphere is called without the input parameter, MATLAB
uses the default value n = 20.
• We can translate the center of the sphere easily.
• In the following example we will plot graph of the unit sphere with
center at (2, -1, 1)
[x,y,z] = sphere(30);
surf(x+2, y-1, z+1)
107. Command Sphere and Cylinder…
• Function sphere together with function surf or mesh can be used to
plot graphs of spheres of arbitrary radii. Also, they can be used to
plot graphs of ellipsoids.
108. Command Sphere and Cylinder…
• Function cylinder is used for plotting a surface of revolution. It takes
two (optional) input parameters.
• In the following command cylinder(r, n) parameter r stands for the
vector that defines the radius of cylinder along the z-axis and n
specifies a number of points used to define circumferenceof the
cylinder.
• Default values of these parameters are r = [1 1] and n = 20.
• A generated cylinder has a unit height.
• The following command
cylinder([1 0])
title('Unit cone')
109. Command Sphere and Cylinder…
• plots a cone with the base radius equal to one and the unit height.
• Example: we will plot a graph of the surface of revolution obtained
by rotating the curve r(t) = < sin(t), t >, 0<t>π about the y-axis.
• Graphs of the generating curve and the surface of revolution are
created using a few lines of the computer code
t = 0:pi/100:pi;
r = sin(t);
plot(r,t)
111. Printing MATLAB Graphics
• To send a current graph to the printer click on File and next select
Print from the pull down menu.
• Once this menu is open we can preview a graph to be printed be
selecting the option PrintPreview…
• We can also send the graph to the printer using the print command
x = 0:0.01:1;
plot(x, x.^2)
print
112. Printing MATLAB Graphics…
• We can print the graphics to an m- file using built-in device drivers.
• A fairly incomplete list of these drivers is included here:
-depsc Level 1 color Encapsulated PostScript
-deps2 Level 2 black and white Encapsulated PostScript
-depsc2 Level 2 color EncapsulatedPostScript
• Suppose that one wants to print a current graph to the m-file Figure1
using level 2 color Encapsulated PostScript. This can be accomplished
by executing the following command
print –depsc2 Figure1
113. Printing MATLAB Graphics…
• You can put this command either inside your m-file or execute it from
within the Command Window.