Home » All » MATLAB Arithmetic Operations and Frequently Used Commands

MATLAB Arithmetic Operations and Frequently Used Commands

MATLAB Arithmetic Operations and Frequently Used Commands

In this section, discussed about MATLAB Arithmetic Operations and Frequently Used Commands specially for Matlab Beginners  such as help, lookfor, which, Scalar Arithmetic Operations, stopping of program, elementary and frequently used math  functions and trigonometric functions.

Subscribe to Thesis123 YouTube Channel for Free and Latest Videos

Getting Help in Matlab

The most useful command in MATLAB is help. This brings up a description of the command you are asking help for.  An example of this is:
>> help det
DET   Determinant.   DET(X) is the determinant of the square matrix X.     Use COND instead of DET to test for matrix singularity.
See also COND. Overloaded methods   help sym/det.m
All examples in this document will have two greater than symbols followed by a command which can be cut and paste into your version of MATLAB.
Note: In the above example, it is asked for help on det and instead, the help page indicates that you should use DET(X). This is explained by the following line from help help
Note: In the online help, keywords are capitalized to make them stand out. Always type commands in lowercase since all command and function names are actually in lowercase.

>> help for

FOR   Repeat statements a specific number of times.The general form of a FOR statement is:         FOR variable = expr, statement, ..., statement END
When asking for help for operators, for example, +, .*, or ', MATLAB will bring up a help page which looks like:
>> help +

Operators and special characters

Arithmetic operators 

plus       - Plus                                    +
uplus     - Unary plus                           +
minus     - Minus                                
uminus     - Unary minus                    
mtimes     - Matrix multiply                  *
In order to find help for the specific operator in question, you must enter the word in the first column. For example, you would use help plus, help times, and help transpose when looking for help on .*, and ', respectively.
Another useful function is lookfor which will search through all the help pages looking for that particular word. This is useful if you know a concept but do not know the name of the function which implements it.


>> lookfor determinant
>> lookfor determinant

DET   Determinant.
DET   Symbolic matrix determinant.

DRAMADAH Matrix of zeros and ones with large determinant or inverse.
The function which tells you where to find the source code for the particular function. Some functions in MATLAB are built in, so their source code is not viewable, but most functions are written using MATLAB code which you can inspect, copy from, and modify:


>> which det
det is a built-in function.
>> which sortrows

To view the source, you can edit the above file.
Note: Like in C and Java, you can assign to variables using =. If you do not assign output to a variable, MATLAB automatically assigns it to the variable ans which is a special variable

>> det( A*A' )   % find the determinant of A multiplied by the transpose of A

ans =     0

Basic Arithmetic Operations PART-A

Arithmetic operations with scalars

The arithmetic operations, symbols used in matlab and examples are given in Table

operation symbol example
Addition + >>5+6ans=11
Subtraction - >>10-3ans=7
Multiplication * >>5*3ans=15
Right division / >>4/2ans=2
Left division \ >>4\2ans=0.5

Saving a session

When one logs out or exits MATLAB all variables are lost. However, invoking the command save before exiting causes all variables to be written to a non-human-readable disk file named MATLAB.mat. When one later reenters MATLAB, the command load will restore the workspace to its former state.

Saving Workspace

Commands :
diary                                 Start saving commands in a file
diary(‘filename’)                 Start saving commands in the file filename
diary off                             Stop the diary
The diary command allows saving all command window inputs and outputs (except graphics) in a separate file, which can be opened with most text editors (e.g. Microsoft Word) and printed.
Example: Start the diary and save the file as mydiary. Compute the number of seconds in one year. Close the diary. Open the file mydiary using any text editor.

In the Command Window :
>> diary(‘mydiary’)
>> 60*60*24*365
ans =
>> diary off
In Microsoft Word :
ans =
diary off

Note:  MATLAB workspace will be saved into a file named diary when no file name is specified.
Note:   If you need help with a specific MATLAB command, simply type help command name in the command window. Detailed information will be displayed with everything needed to use this command properly. If you don’t know the exact name of the command, type lookfor keyword, which returns all the commands related to that keyword.

Stopping execution of a program

A runaway display or computation can be stopped on most machines without leaving MATLAB with CTRL+C (CTRL-BREAK on a PC).

Editing and recall.

The command line in MATLAB can be easily edited. The cursor can be positioned with the left/right arrows and the Backspace (or Delete) key used to delete the character to the left of the cursor. Other editing features are also available. On a PC try the Home, End, and Delete keys; on a Unix system or a PC the Emacs commands Ctl-a, Ctl-e, Ctl-d, and Ctl-k work; on other systems see help cedit or type cedit.
A convenient feature is use of the up/down arrows to scroll through the stack of previous commands. One can, therefore, recall a previous command line, edit it, and execute the revised command line. For small routines, this is much more convenient that using an M-file which requires moving between MATLAB and the editor.
>> m=2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)

Note:   To display the current value of a variable, double-click on its name in the command window.
Note:    To avoid retyping previously used command, use up and down arrows

Elementary Math Functions
>> a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i];
abs       absolute value or complex magnitude
>> abs(a)
ans =
1.9000   0.2000   3.4000   5.6000   7.0000   4.3267
angle   phase angle
>> angle(a) % In radians
ans =
3.1416   3.1416         0         0         0   0.9828
sqrt     square root
>> sqrt(a)
ans =
Columns 1 through 5
0 + 1.3784i 0 + 0.4472i   1.8439             2.3664           2.6458
Column 6
1.8339 + 0.9815i
real        real part
>> real(a)
ans =
-1.9000   -0.2000   3.4000   5.6000   7.0000   2.4000
imag      imaginary part
>> imag(a)
ans =
0         0         0         0         0   3.6000
conj       complex conjugate
>> conj(a)
ans =
Columns 1 through 5
-1.9000 -0.2000 3.4000 5.6000             7.0000
Column 6
2.4000 - 3.6000i
gcd         greatest common divisor
lcm         least common multiple
round    round to nearest integer
>> round(a)
ans =
Columns 1 through 5
-2.0000                 0             3.0000             6.0000             7.0000
Column 6
2.0000 + 4.0000i
fix         round toward zero
>> fix(a)
ans =
Columns 1 through 5
-1.0000                 0             3.0000             5.0000             7.0000
Column 6
2.0000 + 3.0000i
floor      round toward minus infinity
>> floor(a)
ans =
Columns 1 through 5
-2.0000           -1.0000             3.0000             5.0000             7.0000
Column 6
2.0000 + 3.0000i
ceil         round toward infinity
>> ceil(a)
ans =
Columns 1 through 5
-1.0000                 0            4.0000             6.0000             7.0000
Column 6
3.0000 + 4.0000i
sign        signum function
rem        remainder
>> rem(3,2)
ans =
exp        exponential base e
>> exp(6)
ans =
log          natural logarithm
>> log(100)
ans =
log10     log base 10
>> log10(100)
ans =2

Trigonometric Functions

All possible trigonometric functions are available and are listed below

  • sin, asin, sinh, asinh
  • sine, arcsine, hyperbolic sine, hyperbolic arcsine
  • cos, acos, cosh, acosh
  • cosine, arccosine, hyperbolic cosine, hyperbolic arccosine
  • tan, atan, tanh, atanh
  • tangent, arctangent, hyperbolic tangent, hyperbolic arctangent
  • cot, acot, coth, acoth
  • cotangent, arccotangent, hyperbolic cotan., hyperbolic arccotan.
  • sec, asec, sech, asech
  • secant, arcsecant, hyperbolic secant, hyperbolic arcsecant
  • csc, acsc, csch, acsch
  • cosecant, arccosecant, hyperbolic cosecant, hyperbolic arccosecant

>>a=30; >> x=sin(a)

Controlling the Command Window

  • home send cursor home | to top of screen
  • echo echo commands inside script             commands
  • more control paged output in command     window

Working with Files and the Operating System

  • cd change current working directory
  • pwd show current working directory
  • dir, ls directory listing
  • delete delete file
  • getenv get environment variable
  • ! execute operating system command
  • unix execute operating system command;
  • return        result

Managing Variables and the Workspace

  • who - list current variables
  • whos- list current variables, long form
  • save -save workspace variables to disk
  • save;  Save all variable in MATLAB.mat files
  • save filename a b c; Save variables a, b, and c in mat
  • load -retrieve variables from disk
  • load filename; Load a pre-saved file
  • load; Load MATLAB.mat files
  • clear -clear variables and functions from memory
  • pack -consolidate workspace memory
  • size -size of matrix
  • length- length of vector
  • disp -display matrix or text

>>save x
>>load x
>>clear x

Special Characters

=                assignment statement
[ ]               used to form vectors and matrices; enclose multiple function output variables
( )               arithmetic expression precedence; enclose function input variables
.                 Decimal point
..                Parent directory
...               Continue statement to next line
,                 separate subscripts, function arguments, statements
;                 end rows, suppress printing
%               comments
:                 Subscripting, vector generation

Time and Date

date                    current date
clock                   wall clock
etime                  elapsed time function
tic, toc                stopwatch timer functions
cputime              elapsed CPU time

Hints for C Users

Some advice to users of C (or C++):

  • You don't have to declare your variables.
  • Semicolons on the end of lines suppress output.
  • Use & and | instead of && and ||.
  • To get bitwise operations (& and | in C), see this link.
  • Everything is stored as a 2-dimensional array of data.
  • Use parentheses to index into matrices, not brackets, and use A(i, j), not A[i][j].
  • All the operators are overloaded to work with matrices.
  • The comment symbol is % and behaves like //.
  • The output of MATLAB functions can be assigned to vectors of variables, and often this is the only way to coerce the function to return certain outputs.

In general, MATLAB commands cannot span multiple lines unless you are using bracket notation to enter a matrix, or if you type the continuation operator ... before you press Enter.

 Subscribe to Thesis123 YouTube Channel for Free and Latest Videos