Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
MATLAB
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Syntax== The MATLAB application is built around the MATLAB programming language. Common usage of the MATLAB application involves using the "[[Command-line interface|Command Window]]" as an interactive mathematical [[command line interface|shell]] or executing [[Text file|text files]] containing MATLAB code.<ref>{{cite web|url=http://www.mathworks.com/help/matlab/index.html|title=MATLAB Documentation |publisher=MathWorks|access-date=August 14, 2013}}</ref> === "Hello, world!" example === An example of a [["Hello, world!" program]] exists in MATLAB. <syntaxhighlight lang="matlab"> disp('Hello, world!') </syntaxhighlight> It displays like so: <syntaxhighlight lang="output"> Hello, world! </syntaxhighlight> ===Variables=== [[Variable (computer science)|Variables]] are defined using the [[Assignment (computer science)|assignment]] operator, <code>=</code>. MATLAB is a [[Strong and weak typing|weakly typed]] programming language because [[Data type|types]] are implicitly converted.<ref>{{cite web|title=Comparing MATLAB with Other OO Languages|url=http://www.mathworks.com/help/matlab/matlab_oop/matlab-vs-other-oo-languages.html|work=MATLAB|publisher=MathWorks|access-date=August 14, 2013}}</ref> It is an [[Type inference|inferred]] [[Type system|typed language]] because variables can be assigned without declaring their type, except if they are to be treated as symbolic objects,<ref>{{cite web|title=Create Symbolic Variables and Expressions|url=http://www.mathworks.com/help/symbolic/creating-symbolic-variables-and-expressions.html|work=Symbolic Math Toolbox|publisher=MathWorks|access-date=August 14, 2013}}</ref> and that their type can change. Values can come from [[constant (computer science)|constant]]s, from computation involving values of other variables, or from the output of a [[Function (computer programming)|function]]. For example: <syntaxhighlight lang="matlabsession"> >> x = 17 x = 17 >> x = 'hat' x = hat >> x = [3*4, pi/2] x = 12.0000 1.5708 >> y = 3*sin(x) y = -1.6097 3.0000 </syntaxhighlight> === Vectors and matrices === A simple array is defined using the colon syntax: ''initial''<code>:</code>''increment''<code>:</code>''terminator''. For instance: <syntaxhighlight lang="matlabsession"> >> array = 1:2:9 array = 1 3 5 7 9 </syntaxhighlight> defines a variable named <code>array</code> (or assigns a new value to an existing variable with the name <code>array</code>) which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the ''initial'' value), increments with each step from the previous value by 2 (the ''increment'' value), and stops once it reaches (or is about to exceed) 9 (the ''terminator'' value). The ''increment'' value can actually be left out of this syntax (along with one of the colons), to use a default value of 1. <syntaxhighlight lang="matlabsession"> >> ari = 1:5 ari = 1 2 3 4 5 </syntaxhighlight> assigns to the variable named <code>ari</code> an array with the values 1, 2, 3, 4, and 5, since the default value of 1 is used as the increment. [[One-based indexing|Indexing]] is one-based,<ref>{{cite web|title=Matrix Indexing|url=http://www.mathworks.com/help/matlab/math/matrix-indexing.html|publisher=MathWorks|access-date=August 14, 2013}}</ref> which is the usual convention for [[matrix (mathematics)|matrices]] in mathematics, unlike zero-based indexing commonly used in other programming languages such as C, [[C++]], and [[Java (programming language)|Java]]. Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon to separate the rows. The list of elements should be surrounded by square brackets <code>[]</code>. Parentheses <code>()</code> are used to access elements and subarrays (they are also used to denote a function argument list). <syntaxhighlight lang="matlabsession"> >> A = [16, 3, 2, 13 ; 5, 10, 11, 8 ; 9, 6, 7, 12 ; 4, 15, 14, 1] A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> A(2,3) ans = 11 </syntaxhighlight> Sets of indices can be specified by expressions such as <code>2:4</code>, which evaluates to <code>[2, 3, 4]</code>. For example, a submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as: <syntaxhighlight lang="matlabsession"> >> A(2:4,3:4) ans = 11 8 7 12 14 1 </syntaxhighlight> A square [[identity matrix]] of size ''n'' can be generated using the function <code>eye</code>, and matrices of any size with zeros or ones can be generated with the functions <code>zeros</code> and <code>ones</code>, respectively. <syntaxhighlight lang="matlabsession"> >> eye(3,3) ans = 1 0 0 0 1 0 0 0 1 >> zeros(2,3) ans = 0 0 0 0 0 0 >> ones(2,3) ans = 1 1 1 1 1 1 </syntaxhighlight> [[Transpose|Transposing]] a vector or a matrix is done either by the function <code>transpose</code> or by adding dot-prime after the matrix (without the dot, prime will perform [[conjugate transpose]] for complex arrays): <syntaxhighlight lang="matlabsession"> >> A = [1 ; 2], B = A.', C = transpose(A) A = 1 2 B = 1 2 C = 1 2 >> D = [0, 3 ; 1, 5], D.' D = 0 3 1 5 ans = 0 1 3 5 </syntaxhighlight> Most functions accept arrays as input and operate element-wise on each element. For example, <code>mod(2*J,n)</code> will multiply every element in ''J'' by 2, and then reduce each element modulo ''n''. MATLAB does include standard <code>for</code> and <code>while</code> loops, but (as in other similar applications such as [[APL (programming language)|APL]] and [[R (programming language)|R]]), using the [[Array programming|vectorized]] notation is encouraged and is often faster to execute. The following code, excerpted from the function ''magic.m'', creates a [[magic square]] ''M'' for odd values of ''n'' (MATLAB function <code>meshgrid</code> is used here to generate square matrices {{mvar|I}} and {{mvar|J}} containing {{tmath|1:n}}): <syntaxhighlight lang="matlab"> [J,I] = meshgrid(1:n); A = mod(I + J - (n + 3) / 2, n); B = mod(I + 2 * J - 2, n); M = n * A + B + 1; </syntaxhighlight> === Structures === MATLAB supports structure data types.<ref>{{cite web|title=Structures|url=http://www.mathworks.com/help/matlab/structures.html|publisher=MathWorks|access-date=August 14, 2013}}</ref> Since all variables in MATLAB are arrays, a more adequate name is "structure array", where each element of the array has the same field names. In addition, MATLAB supports dynamic field names<ref>{{cite web|title=Generate Field Names from Variables|url=http://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html|publisher=MathWorks|access-date=August 14, 2013}}</ref> (field look-ups by name, field manipulations, etc.). === Functions === When creating a MATLAB function, the name of the file should match the name of the first function in the file. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores. Variables and functions are case sensitive.<ref>{{cite web|title=Case and Space Sensitivity|url=https://www.mathworks.com/help/matlab/matlab_prog/case-and-space-sensitivity.html|publisher=MathWorks|access-date=November 1, 2019}}</ref> {{sxhl|2=matlab|1= rgbImage = imread('ecg.png'); grayImage = rgb2gray(rgbImage); % for non-indexed images level = graythresh(grayImage); % threshold for converting image to binary, binaryImage = im2bw(grayImage, level); % Extract the individual red, green, and blue color channels. redChannel = rgbImage(:, :, 1); greenChannel = rgbImage(:, :, 2); blueChannel = rgbImage(:, :, 3); % Make the black parts pure red. redChannel(~binaryImage) = 255; greenChannel(~binaryImage) = 0; blueChannel(~binaryImage) = 0; % Now recombine to form the output image. rgbImageOut = cat(3, redChannel, greenChannel, blueChannel); imshow(rgbImageOut); }} === Function handles === MATLAB supports elements of [[lambda calculus]] by introducing function handles,<ref>{{cite web|title=Function Handles|url=http://www.mathworks.com/help/matlab/function-handles.html|publisher=MathWorks|access-date=August 14, 2013}}</ref> or function references, which are implemented either in .m files or anonymous<ref>{{cite web|title=Anonymous Functions|url=http://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html|publisher=MathWorks|access-date=August 14, 2013}}</ref>/nested functions.<ref>{{cite web|title=Nested Functions|url=http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html|publisher=MathWorks.}}</ref> === Classes and object-oriented programming === MATLAB supports [[object-oriented programming]] including classes, [[inheritance (object-oriented programming)|inheritance]], virtual dispatch, packages, [[pass-by-value]] semantics, and [[pass-by-reference]] semantics.<ref>{{cite web|url=http://www.mathworks.com/help/matlab/object-oriented-programming.html |title=Object-Oriented Programming|publisher=MathWorks|access-date=August 14, 2013}}</ref> However, the syntax and calling conventions are significantly different from other languages. MATLAB has value classes and reference classes, depending on whether the class has ''handle'' as a super-class (for reference classes) or not (for value classes).<ref>{{cite web|title=Comparing Handle and Value Classes|url=http://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html|publisher=MathWorks}}</ref> Method call behavior is different between value and reference classes. For example, a call to a method: <syntaxhighlight lang="matlab"> object.method(); </syntaxhighlight> can alter any member of ''object'' only if ''object'' is an instance of a reference class, otherwise value class methods must return a new instance if it needs to modify the object. An example of a simple class is provided below: <syntaxhighlight lang="matlab"> classdef Hello methods function greet(obj) disp('Hello!') end end end </syntaxhighlight> When put into a file named <code>hello.m</code>, this can be executed with the following commands: <syntaxhighlight lang="matlabsession"> >> x = Hello(); >> x.greet(); Hello! </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)