2: Basic Commands in MATLAB (2024)

  1. Last updated
  2. Save as PDF
  • Page ID
    89345
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}}}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}}}\)

    \( \newcommand{\vectorC}[1]{\textbf{#1}}\)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}}\)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}}\)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}}}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    Introduction

    To get started writing code in MATLAB, several commands are essential to begin to operate the program. A command is a basic instruction that the user gives the program. These instructions, if given correctly, cause MATLAB to output a response such as printing a solution to a problem, executing a step in a larger process, or relaying information about the code. This chapter details several common commands which will frequently be used when writing scripts. The MATLAB user interface includes a command window designed specifically to facilitate the user executing simple commands or interacting with specific parts of larger codes, which will be addressed in the discussion of scripts. The command window and commands as a concept are fundamental concepts for coding. As a result, the following chapter has been written to instruct users on the variety, effects, and syntax required for command use in the broader context of MATLAB.

    Help Resources

    MATLAB is a complicated programming tool that contains many functions which can be used in an assortment of applications.

    When writing code for ME 160, there are several ways for the user to learn more about functions and their operations while writing code. When the user knows the name of a command and is wanting to learn more about its function or how it should be written into the code, the user should use the help command. For example, to learn more about the if function, the user would time help if into the command window.

    2: Basic Commands in MATLAB (1)

    Many other resources exist outside of the program within both the MathWorks’ webpage and resources produced by third-party vendors. Appendix I of this text discusses many resources that are provided outside of MATLAB software itself. Specifically, resources provided within the documentation page are most valuable within the context of ME 160. The documentation page for a specific function can be reached by following the hyperlink at the bottom of the help page in MATLAB or by searching for the “MathWorks MATLAB Documentation” in a search engine.

    As the reader is most likely just beginning to code in MATLAB, interactive tutorials offered on the MathWorks webpage may prove as valuable supplements to in-class work. Mathworks has provided many interactive MATLAB coding tutorials which enable the user to walk through exercises in a virtual “MATLAB Onramp” course. For more information about MathWorks interactive programs, refer to Appendix I at the end of this text.

    Comments

    Comments are a built-in way MATLAB has enabled users to make notes within a code without affecting the code’s function. To make a comment within a code, the user can type % at the beginning of a line of code. MATLAB will then ignore everything typed after that percent sign, enabling the user to type information regarding the function of the code or what a part of the code does. Comments are essential to writing efficient, long codes that can easily be read and edited by both the initial author and their peers. By placing many comments throughout codes in ME 160, the author will ensure that the code is easily read and edited by themselves, their peers, and the faculty grading final codes. Forming the habit of commenting often throughout a code is critical to ensuring that codes produced within ME 160 are useful and effective.

    Comments have also been designed to help users who are editing code and would like to “turn off” a section of code. In the instance that a section of code within a MATLAB script does not work or should not be run, the user could place comments with % signs at the beginning of each line that should be ignored by the code. In order to speed up the process of “commenting out” large sections of code, MATLAB has created the notation %{ and %} which can be placed on different lines of code and will comment everything written in lines of code between the symbols. An example of standard comments and a block comment follows below. In the example, a portion of code that does not work correctly has been commented out and a note to correct the code has been made. Comments such as the one in line three are essential to ensure that codes are as legible as possible for all users.

    2: Basic Commands in MATLAB (2)

    Arithmetic in MATLAB

    MATLAB is a well-versed tool for completing simple mathematical operations or solving algebraic equations. To complete these operations, the user must be aware of the notation that is required for the computer to understand what was input.

    General Operations

    To complete addition, subtraction, multiplication, or division the user must be precise with how they write their expressions. The included image depicts how to properly input operations. The first thing the user should be mindful of is the lack of an equal sign in mathematical operations. MATLAB uses single equal signs to assign a value to a variable, which is not what we2: Basic Commands in MATLAB (3) want to do when solving an expression. Instead, press enter without typing an equal sign to tell MATLAB to solve the expression. Note that operations do not depend on if spaces are present between the numerical values and the operator. For multiplication and division note the use of an asterisk (*) and a forward slash (/) as their respective operators. Several operations can be done by inputting values with consideration of conventional order of operations rules (think the acronym PEMDAS for parenthesis, exponents, multiplication, division, addition, and subtraction if you forget).

    Exponents and roots can be calculated in a similar manner in MATLAB. To compute an operation with an exponent, use a caret (^) followed by the value of the power. To compute roots, the same notation can be used with the root depicted as an exponent. For example, four squared could be written as 4^2 in MATLAB and the square root of four could be written as either 4^(1/2). The sqrt function can also be written using the sqrt() function, with all values which would be under the radical being contained within the parenthesis.

    Calculating expressions using logarithms and exponentials are easy using MATLAB as well. To calculate a base 10 logarithm, use the function “log(x)” with x being the numerical value of the logarithm. In a similar manner, values taken to a power of e can be written using “exp(x)”, which would be input as “exp(4)” in MATLAB.

    Trigonometry in MATLAB

    MATLAB defaults to using radians to calculate degrees, which requires the user to be careful when entering angles to ensure the value is not calculated incorrectly. The functions degree() and radian() can be used to convert between an angle in degrees and an angle in radians. When computing trigonometry operations such as sin() or cos() in MATLAB, the alternative function sind(), cosd(), or tand() can be used to inform MATLAB that the value entered in the trigonometry operation is in degrees. This saves the user the need to convert between radians and degrees.

    Complex Expressions

    MATLAB can calculate complex expressions in the same manner as simple expressions. MATLAB, like any traditional calculator, calculates specifically based on what the user inputs. While expressions are input using the same formatting regardless of their complexity, it is increasingly important to consider the order of operations that the system will use as a result of parenthesis or the lack thereof placed by the user. To get a feel for typing complex expressions within MATLAB’s command window, review the following examples and reproduce them within MATLAB yourself.

    Examples

    The following examples demonstrate how to input complex expressions into the command window.

    1. 2: Basic Commands in MATLAB (4)

    2: Basic Commands in MATLAB (5)

    1. 2: Basic Commands in MATLAB (6)

    2: Basic Commands in MATLAB (7)

    1. 2: Basic Commands in MATLAB (8)

    2: Basic Commands in MATLAB (9)

    1. 2: Basic Commands in MATLAB (10)

    2: Basic Commands in MATLAB (11)

    1. 2: Basic Commands in MATLAB (12)

    2: Basic Commands in MATLAB (13)

    Problems

    Practice writing the following expressions in MATLAB. Be careful to use proper parenthesis and order of operations. For problem 5, show each equation being solved using MATLAB.

    1. 2: Basic Commands in MATLAB (14)
    1. 2: Basic Commands in MATLAB (15)
    1. 2: Basic Commands in MATLAB (16)
    1. 2: Basic Commands in MATLAB (17)
    1. The velocity of an object is represented by the following function:

    \[V\left(t\right)=\sqrt[3]{4t^3+\frac{1}{2}t^2+2t+100}\]

    Using MATLAB, determine the velocity of the object at times t = 10 seconds, 50 seconds, and 100 seconds. (Note: While this problem may be more easily solved using a calculator, MATLAB could be used in the future to calculate the velocity at many different times. To create that code, the author would need to correctly input the function, which is what this problem exercises.)

    1. A titanium ball is dropped into a viscous fluid and slowly sinks to the bottom. A 5 mm diameter spherical ball is dropped into the liquid at a constant speed such that it takes 5 seconds for the ball to drop .15m. The density of titanium is 4402: Basic Commands in MATLAB (18) and the density of the fluid is 800 2: Basic Commands in MATLAB (19). Determine the viscosity of the fluid using the following equations. Note that D is the sphere’s diameter, 2: Basic Commands in MATLAB (20) (rho) is density, 2: Basic Commands in MATLAB (21) is gravitational acceleration, (9.8 m/s), and 2: Basic Commands in MATLAB (22) is the change of the ball’s height.

    \[V_{sphere}=\ \frac{\pi(D^3)}{6}\]

    \[Weight\ of\ Sphere=W=\rho_{sphere}g(\Delta h)\]

    \[Weight\ of\ Sphere=W=\rho_{sphere}g(\Delta h)\]

    \[Weight\ of\ Sphere=W=\rho_{sphere}g(\Delta h)\]

    \[Viscosity=\mu=\frac{F_D}{3\pi(D)(Velocity)}\]

    2: Basic Commands in MATLAB (2024)

    FAQs

    2: Basic Commands in MATLAB? ›

    There are several types of functions available with MATLAB®, including local functions, nested functions, private functions, and anonymous functions. To determine which function to call when multiple functions in the current scope have the same name, MATLAB uses function precedence order.

    What are the basic functions of MATLAB? ›

    There are several types of functions available with MATLAB®, including local functions, nested functions, private functions, and anonymous functions. To determine which function to call when multiple functions in the current scope have the same name, MATLAB uses function precedence order.

    What is the or command in MATLAB? ›

    A | B represents the logical OR. A | B is true when either A or B is true, or when both A and B are true. or( A , B ) is equivalent to A | B .

    What is the write command in MATLAB? ›

    write( device , data , datatype ) writes the row or column vector data to the specified serial port connection device . The function writes the data in the specified data type datatype , regardless of the format in data . The function suspends MATLAB® execution until the specified values are written.

    What are the basic operations of MATLAB? ›

    Basic Arithmetic
    • Addition. + Add numbers, append strings. sum. Sum of array elements. ...
    • Subtraction. - Subtraction. diff. ...
    • Multiplication. .* Multiplication. * ...
    • Division. ./ Right array division. .\ ...
    • Powers. .^ Element-wise power. ^ ...
    • Transpose. .' Transpose vector or matrix. ' ...
    • Array Sign. uminus. Unary minus. uplus.

    What is MATLAB basic features? ›

    Key Features
    • High-level language for scientific and engineering computing.
    • Desktop environment tuned for iterative exploration, design, and problem-solving.
    • Graphics for visualizing data and tools for creating custom plots.

    What is the basic application of MATLAB? ›

    Applications
    • Image Processing and Computer Vision. Extend deep learning workflows with image processing, computer vision, medical imaging, lidar, and automated driving applications.
    • Signal Processing, Audio, and Wireless. ...
    • Autonomous and Control Systems. ...
    • Text Analytics and Computational Finance.

    What is MATLAB syntax? ›

    With command syntax, MATLAB passes all inputs as character vectors (that is, as if they were enclosed in single quotation marks) and does not assign outputs to user defined variables. If the function returns an output, it is assigned to the ans variable.

    How do I run a command in MATLAB? ›

    Go to the Editor tab and click Run . MATLAB® displays the list of commands available for running the function. Click the last item in the list and replace the text type code to run with a call to the function including the required input arguments.

    What is mean command in MATLAB? ›

    M = mean( A ) returns the mean of the elements of A along the first array dimension whose size is greater than 1. If A is a vector, then mean(A) returns the mean of the elements. If A is a matrix, then mean(A) returns a row vector containing the mean of each column.

    What is system command in MATLAB? ›

    System commands provide programmatic access to your operating system and the MATLAB environment. Using these commands, you can access information about your computer, copy content to the system clipboard, get and set environment variables, and execute operating system commands.

    What is function command in MATLAB? ›

    Functions in MATLAB are defined in separate files and should have the same name as the file. These functions operate on variables within their workspace, called the local workspace. This local workspace is separate from the workspace you access at the MATLAB command prompt, called the base workspace.

    What is text command in MATLAB? ›

    The text function creates one text object for each text description. Thus, t contains two text objects. Change the color and font size for the first text object using t(1) . Use dot notation to set properties. If you are using an earlier release, use the set function instead.

    What is a command line in MATLAB? ›

    The command-line interface provides an interactive environment that you can extend. The MATLAB command-line interface includes: Environment — Configure target computers and change the environment properties without using a graphical interface.

    What are the main uses of MATLAB? ›

    Millions of engineers and scientists worldwide use MATLAB for a range of applications, in industry and academia, including deep learning and machine learning, signal processing and communications, image and video processing, control systems, test and measurement, computational finance, and computational biology.

    What are the mathematical functions in MATLAB? ›

    Elementary Mathematical Functions
    round(x)Rounds x to the nearest integer
    sign(x)Returns -1 if x; returns 0 if x=0; returns 1 if x>0.
    rand or rand(1)Generates a random number between 0 and 1
    exp(x)Exponential function ex
    log(x)Natural logarithm function, y=lnx (where ey=x)
    8 more rows

    What is any function in MATLAB? ›

    The any function reduces such a vector of logical values to a single condition. In this case, B = any(A < 0.5) yields logical 1 . This makes any particularly useful in if statements.

    References

    Top Articles
    Latest Posts
    Article information

    Author: Virgilio Hermann JD

    Last Updated:

    Views: 5721

    Rating: 4 / 5 (41 voted)

    Reviews: 88% of readers found this page helpful

    Author information

    Name: Virgilio Hermann JD

    Birthday: 1997-12-21

    Address: 6946 Schoen Cove, Sipesshire, MO 55944

    Phone: +3763365785260

    Job: Accounting Engineer

    Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

    Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.