In many cases, you may want to change the behavior of the MATLAB operators and functions for cases when the arguments are objects. You can accomplish this by overloading the relevant functions. Overloading enables a function to handle different types and numbers of input arguments and perform whatever operation is appropriate for the highest-precedence object. See Object Precedence for more information on object precedence.

Each built-in MATLAB operator has an associated function name (e.g., the + operator has an associated plus.m function). You can overload any operator by creating an M-file with the appropriate name in the class directory. For example, if either p or q is an object of type class_name , the expression

generates a call to a function @ class_name /plus.m , if it exists. If p and q are both objects of different classes, then MATLAB applies the rules of precedence to determine which method to use.

See the following sections for examples of overloaded operators:

  • Overloading the + Operator
  • Overloading the - Operator
  • Overloading the * Operator





Binary addition


Binary subtraction


Unary minus


Unary plus


Element-wise multiplication


Matrix multiplication


Right element-wise division


Left element-wise division


Matrix right division


Matrix left division


Element-wise power


Matrix power


Less than


Greater than


Less than or equal to


Greater than or equal to


Not equal to


Equality


Logical AND


Logical OR


Logical NOT




Colon operator


Complex conjugate transpose


Matrix transpose


Display method


Horizontal concatenation


Vertical concatenation


Subscripted reference


Subscripted assignment


Subscript index
  Converter Methods Overloading Functions 

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons

Margin Size

  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

1.1: Operators and Special Characters

  • Last updated
  • Save as PDF
  • Page ID 86616

\( \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{\kernel}{\mathrm{null}\,}\)

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

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

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

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

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

\( \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}}}} \)

Plus; addition operator.

Minus; subtraction operator.

Scalar and matrix multiplication operator.

.* 

Array multiplication operator.

Scalar and matrix exponentiation operator.

.^ 

Array exponentiation operator.

Left-division operator.

Right-division operator.

.\ 

Array left-division operator.

./ 

Array right-division operator.

Colon; generates regularly spaced elements and represents an entire row or column.

( ) 

Parentheses; encloses function arguments and array indices; overrides precedence.

[ ] 

Brackets; enclosures array elements.

Decimal point.

… 

Ellipsis; line-continuation operator.

Comma; separates statements and elements in a row.

Semicolon; separates columns and suppresses display.

Percent sign; designates a comment and specifies formatting.

Quote sign and transpose operator.

._ 

Nonconjugated transpose operator.

Assignment (replacement) operator.

Help Center Help Center

  • Help Center
  • Mises à jour du produit
  • Documentation

Creating a Simple Class

Design class.

The basic purpose of a class is to define an object that encapsulates data and the operations performed on that data. For example, BasicClass defines a property and two methods that operate on the data in that property:

Value — Property that contains the numeric data stored in an object of the class

roundOff — Method that rounds the value of the property to two decimal places

multiplyBy — Method that multiplies the value of the property by the specified number

Start a class definition with a classdef ClassName ...end block, and then define the class properties and methods inside that block. Here is the definition of BasicClass :

For a summary of class syntax, see classdef .

To use the class:

Save the class definition in a .m file with the same name as the class.

Create an object of the class.

Access the properties to assign data.

Call methods to perform operation on the data.

Create Object

Create an object of the class using the class name:

Initially, the property value is empty.

Access Properties

Assign a value to the Value property using the object variable and a dot before the property name:

To return a property value, use dot notation without the assignment:

For information on class properties, see Property Syntax .

Call Methods

Call the roundOff method on object a :

Pass the object as the first argument to a method that takes multiple arguments, as in this call to the multiplyBy method:

You can also call a method using dot notation:

Passing the object as an explicit argument is not necessary when using dot notation. The notation uses the object to the left of the dot.

For information on class methods, see Method Syntax .

Add Constructor

Classes can define a special method to create objects of the class, called a constructor. Constructor methods enable you to pass arguments to the constructor, which you can assign as property values. The BasicClass Value property restricts its possible values using the mustBeNumeric function.

Here is a constructor for the BasicClass class. When you call the constructor with an input argument, it is assigned to the Value property. If you call the constructor without an input argument, the Value property has a default value of empty ( [] ).

By adding this constructor to the class definition, you can create an object and set the property value in one step:

The constructor can perform other operations related to creating objects of the class.

For information on constructors, see Class Constructor Methods .

Vectorize Methods

MATLAB ® enables you to vectorize operations. For example, you can add a number to a vector:

MATLAB adds the number 2 to each of the elements in the array [1 2 3] . To vectorize the arithmetic operator methods, enclose the obj.Value property reference in brackets.

This syntax enables the method to work with arrays of objects. For example, create an object array using indexed assignment.

These two expressions are equivalent.

The roundOff method is vectorized because the property reference is enclosed in brackets. r = round([obj.Value],2); Because roundOff is vectorized, it can operate on arrays.

Overload Functions

Classes can implement existing functionality, such as addition, by defining a method with the same name as the existing MATLAB function. For example, suppose that you want to add two BasicClass objects. It makes sense to add the values of the Value properties of each object.

Here is an overloaded version of the MATLAB plus function. It defines addition for the BasicClass class as adding the property values:

By implementing a method called plus , you can use the “ + ” operator with objects of BasicClass .

By vectorizing the plus method, you can operate on object arrays. a = BasicClass(pi/3); b = BasicClass(pi/4); c = BasicClass(pi/2); ar = [a b]; ar + c ans = 2.6180 2.3562

Related Information

For information on overloading functions, see Overload Functions in Class Definitions .

For information on overloading operators, see Operator Overloading .

BasicClass Code Listing

Here is the BasicClass definition after adding the features discussed in this topic:

Related Topics

  • Components of a Class
  • Validate Property Values

Commande MATLAB

Vous avez cliqué sur un lien qui correspond à cette commande MATLAB :

Pour exécuter la commande, saisissez-la dans la fenêtre de commande de MATLAB. Les navigateurs web ne supportent pas les commandes MATLAB.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

  • Switzerland (English)
  • Switzerland (Deutsch)
  • Switzerland (Français)
  • 中国 (English)

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

  • América Latina (Español)
  • Canada (English)
  • United States (English)
  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)

Contact your local office

Help Center Help Center

  • Hilfe-Center
  • Produkt-Updates
  • Documentation

Creating a Simple Class

Design class.

The basic purpose of a class is to define an object that encapsulates data and the operations performed on that data. For example, BasicClass defines a property and two methods that operate on the data in that property:

Value — Property that contains the numeric data stored in an object of the class

roundOff — Method that rounds the value of the property to two decimal places

multiplyBy — Method that multiplies the value of the property by the specified number

Start a class definition with a classdef ClassName ...end block, and then define the class properties and methods inside that block. Here is the definition of BasicClass :

For a summary of class syntax, see classdef .

To use the class:

Save the class definition in a .m file with the same name as the class.

Create an object of the class.

Access the properties to assign data.

Call methods to perform operation on the data.

Create Object

Create an object of the class using the class name:

Initially, the property value is empty.

Access Properties

Assign a value to the Value property using the object variable and a dot before the property name:

To return a property value, use dot notation without the assignment:

For information on class properties, see Property Syntax .

Call Methods

Call the roundOff method on object a :

Pass the object as the first argument to a method that takes multiple arguments, as in this call to the multiplyBy method:

You can also call a method using dot notation:

Passing the object as an explicit argument is not necessary when using dot notation. The notation uses the object to the left of the dot.

For information on class methods, see Method Syntax .

Add Constructor

Classes can define a special method to create objects of the class, called a constructor. Constructor methods enable you to pass arguments to the constructor, which you can assign as property values. The BasicClass Value property restricts its possible values using the mustBeNumeric function.

Here is a constructor for the BasicClass class. When you call the constructor with an input argument, it is assigned to the Value property. If you call the constructor without an input argument, the Value property has a default value of empty ( [] ).

By adding this constructor to the class definition, you can create an object and set the property value in one step:

The constructor can perform other operations related to creating objects of the class.

For information on constructors, see Class Constructor Methods .

Vectorize Methods

MATLAB ® enables you to vectorize operations. For example, you can add a number to a vector:

MATLAB adds the number 2 to each of the elements in the array [1 2 3] . To vectorize the arithmetic operator methods, enclose the obj.Value property reference in brackets.

This syntax enables the method to work with arrays of objects. For example, create an object array using indexed assignment.

These two expressions are equivalent.

The roundOff method is vectorized because the property reference is enclosed in brackets. r = round([obj.Value],2); Because roundOff is vectorized, it can operate on arrays.

Overload Functions

Classes can implement existing functionality, such as addition, by defining a method with the same name as the existing MATLAB function. For example, suppose that you want to add two BasicClass objects. It makes sense to add the values of the Value properties of each object.

Here is an overloaded version of the MATLAB plus function. It defines addition for the BasicClass class as adding the property values:

By implementing a method called plus , you can use the “ + ” operator with objects of BasicClass .

By vectorizing the plus method, you can operate on object arrays. a = BasicClass(pi/3); b = BasicClass(pi/4); c = BasicClass(pi/2); ar = [a b]; ar + c ans = 2.6180 2.3562

Related Information

For information on overloading functions, see Overload Functions in Class Definitions .

For information on overloading operators, see Operator Overloading .

BasicClass Code Listing

Here is the BasicClass definition after adding the features discussed in this topic:

Related Topics

  • Components of a Class
  • Validate Property Values

MATLAB-Befehl

Sie haben auf einen Link geklickt, der diesem MATLAB-Befehl entspricht:

Führen Sie den Befehl durch Eingabe in das MATLAB-Befehlsfenster aus. Webbrowser unterstützen keine MATLAB-Befehle.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

  • Switzerland (English)
  • Switzerland (Deutsch)
  • Switzerland (Français)
  • 中国 (English)

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

  • América Latina (Español)
  • Canada (English)
  • United States (English)
  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)

Contact your local office

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

how can I do a *= operator in matlab

I'm trying to do in Matlab: X = X*-1;

this syntax is a bit annoying, is there a way to do this some other way (like in c++ : x*=-1)

  • matlab-guide

Shai Zarzewski's user avatar

  • 1 AFAIK the answer is NO ! –  P0W Nov 30, 2013 at 16:01
  • 2 Related (if not possibly duplicate): What is the equivalent to += in MATLAB? . Matlab does not support compound assignment operators . –  horchler Nov 30, 2013 at 16:28

2 Answers 2

Unfortunately there are no increment and compound assignment operators in Matlab. I also remember reading posts by employees at Mathworks saying that they don't intend to add such operators to Matlab.

Steve Lord's reply to the following question illustrates the difficulties involved (way down, reply nr 10 or so): http://www.mathworks.com/matlabcentral/newsreader/view_thread/107451

kamjagin's user avatar

  • The link is down, "As of December 2017 the Newsreader application has been shut down." May I know his reply? –  Unknown123 Nov 20, 2018 at 9:47
  • @Unknown123 Wayback Machine has a snapshot –  Ruslan Nov 6, 2021 at 8:41

There is another way! ;-)

Seriously though, I think it's just a matter of habit. There's nothing inherently wrong with that syntax, you are just used to do it differently.

A. Donda's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged matlab matlab-guide or ask your own question .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Has ever a country by its own volition refused to join United Nations, or those which havent joined it's because they aren't recognized as such by UN?
  • Geometric Brownian Motion as the limit of a Binomial Tree?
  • I am international anyway
  • How can I tell whether an HDD uses CMR or SMR?
  • Airplane Owner, But don't have PPL. Can student pilot do oil change on their own plane?
  • Calculating the fibres of a scheme morphism are proper but the morphism is not proper
  • Draw Memory Map/Layout/Region in TikZ
  • Book recommendation introduction to model theory
  • Have I ruined my AC by running it with the outside cover on?
  • Movie I saw in the 80s where a substance oozed off of movie stairs leaving a wet cat behind
  • What is the domain of the dual map of a quantum channel?
  • Do reflective warning triangles blow away in wind storms?
  • Does retirement (pre-Full Retirement Age) qualify for a special enrollment period for the affordable care act?
  • How to convert units when calculating a dimensionless quantity?
  • Why is the Mean Value Theorem called "Gauss's"?
  • What does "far right tilt" actually mean in the context of the EU in 2024?
  • ytableau specify boxframe for each \ydiagram
  • A trigonometric equation: how hard could it be?
  • Why is "second" an adverb in "came a close second"?
  • What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?
  • sculpt mode symmetry mirror mode not working
  • where does the condition of aggregate demand can be written as function of aggregate wealth come from
  • How to make instanced primitives' max/min coordinates to not be higher/lower than input mesh? (geometry nodes)
  • What terminal did David connect to his IMSAI 8080?

matlab class assignment operator

Help Center Help Center

  • Help Center
  • Trial Software
  • Product Updates
  • Documentation

Operators and Elementary Operations

The MATLAB ® language uses many common operators and special characters that you can use to perform simple operations on arrays of any type. See MATLAB Operators and Special Characters for a comprehensive summary.

Operator Basics

  • MATLAB Operators and Special Characters
  • Operator Precedence
  • Array vs. Matrix Operations
  • Compatible Array Sizes for Basic Operations
  • Arithmetic Operations Addition, subtraction, multiplication, division, power, rounding
  • Relational Operations Value comparisons
  • Logical (Boolean) Operations True or false conditions
  • Set Operations Unions, intersection, set membership
  • Bit-Wise Operations Set, shift, or compare specific bit fields

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

  • Switzerland (English)
  • Switzerland (Deutsch)
  • Switzerland (Français)
  • 中国 (English)

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

  • América Latina (Español)
  • Canada (English)
  • United States (English)
  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)

Contact your local office

IMAGES

  1. how to use assignment operator in the matlab coding

    matlab class assignment operator

  2. PPT

    matlab class assignment operator

  3. Matlab Assignment Operator

    matlab class assignment operator

  4. Matlab Basics: The Assignment Operator

    matlab class assignment operator

  5. Lecture 1a: Assignment Operator in MATLAB

    matlab class assignment operator

  6. How to use MATLAB Operators?

    matlab class assignment operator

VIDEO

  1. SCIENTIFIC COMPUTING USING MATLAB WEEK 3 ASSIGNMENT-3 ANSWERS #NPTEL #WEEK-3 #ANSWERS #2024

  2. Lec2: MATLAB: Creating a Variable , Assignment Operator, Clear all, clc

  3. how to use the Logical And Assignment Operator (&&=) #coding #javascript #tutorial #shorts

  4. 28- Assignment and Compound assignment operators (Arabic)

  5. MATLAB Assignment Help

  6. MTH643 Introduction to MATLAB Assignment 1 Spring 2024 Virtual University of Pakistan

COMMENTS

  1. Operator Overloading

    Operator Overloading Why Overload Operators. By implementing operators that are appropriate for your class, you can integrate objects of your class into the MATLAB ® language. For example, objects that contain numeric data can define arithmetic operations like +, *, -so that you can use these objects in arithmetic expressions. By implementing relational operators, you can use objects in ...

  2. oop

    It's not possible to overload the = operator to do this. But (as you probably realised) there's no reason why you can't implement your assign method as you have done, and then call n = assign(m). answered Nov 22, 2011 at 12:53. Sam Roberts. 24.1k 1 41 64.

  3. Using builtin assignment for classes that overload the assignment

    Using builtin assignment for classes that... Learn more about overload, buil in, assign, set method, =, oop ... Using builtin assignment for classes that overload the assignment operator '=' Follow 5 views (last 30 days) Show older comments. Daniel on 5 Apr 2015. Vote. 0. ... MATLAB Programming Classes Construct and Work with Object Arrays.

  4. MATLAB Classes and Objects (Programming and Data Types)

    Overloading Operators. Each built-in MATLAB operator has an associated function name (e.g., the + operator has an associated plus.m function). You can overload any operator by creating an M-file with the appropriate name in the class directory. For example, if either p or q is an object of type class_name, the expression. p + q

  5. Assignment vs Equality

    An assignment statement is used to assign a value to a variable name. Once the value has been assigned, the variable name can be used instead of the value. Matlab allows a variable to be assigned to a single scalar value, or an array of values. You will learn more about arrays in later lessons. The = sign is the assignment operator in Matlab ...

  6. PDF Lecture 5 Advanced MATLAB: Object-Oriented Programming

    OOP in MATLAB Class De nition and Organization Classes Assignment: polynomial In polynomial.m, implement plusto overload the +operator to return p 3 (x) = 1) + 2(x) minusto overload the (operator to return p 3 (x) = 1 x) p 2) differentiateto return p0(x) integrateto return R p(x) dx Then, de ne p 1(x) = 10x2 + x 3 and p 2(x) = 2x3 x+ 9. Use the ...

  7. MATLAB 3-Assignment operators and Arrays

    Assignment operators 1:10, Arrays 40:00, creating a vector with constant spacing (with colon) 44:00, Creating a vector with constant spacing by specifying th...

  8. 1.1: Operators and Special Characters

    Array left-division operator. ./. Array right-division operator. Colon; generates regularly spaced elements and represents an entire row or column. Parentheses; encloses function arguments and array indices; overrides precedence. Brackets; enclosures array elements. Decimal point. Ellipsis; line-continuation operator.

  9. Creating a Simple Class

    obj.Value = val; end end end. By adding this constructor to the class definition, you can create an object and set the property value in one step: a = BasicClass(pi/3) a =. BasicClass with properties: Value: 1.0472. The constructor can perform other operations related to creating objects of the class.

  10. Class Constructor Methods

    MATLAB ® classes that do not explicitly define any class constructors have a default constructor method. This method returns an object of the class that is created with no input arguments. A class can define a constructor method that overrides the default constructor. An explicitly defined constructor can accept input arguments, initialize ...

  11. MATLAB Quick Reference

    Nonconjugated transpose operator. = Assignment (replacement) operator. Commands for Managing a Session. clc: Clears Command window. clear: Removes variables from memory. ... Lists all MATLAB files in the current directory. wklread: ... class: Returns the class of an expression.

  12. Creating a Simple Class

    r = [obj.Value]*n; end end end. For a summary of class syntax, see classdef. To use the class: Save the class definition in a .m file with the same name as the class. Create an object of the class. Access the properties to assign data. Call methods to perform operation on the data.

  13. how can I do a *= operator in matlab

    Unfortunately there are no increment and compound assignment operators in Matlab. I also remember reading posts by employees at Mathworks saying that they don't intend to add such operators to Matlab. Steve Lord's reply to the following question illustrates the difficulties involved (way down, ...

  14. Operators and Elementary Operations

    Operators and Elementary Operations. Arithmetic, relational, and logical operators, special characters, rounding, set functions. The MATLAB ® language uses many common operators and special characters that you can use to perform simple operations on arrays of any type. See MATLAB Operators and Special Characters for a comprehensive summary.