Help Center
- Documentation
- Trial software
- Product updates
Array Indexing
In MATLAB®, there are three primary approaches to accessing array elements based on their location (index) in the array. These approaches are indexing by position, linear indexing, and logical indexing. You can also use mixed indexing by combining both positional and logical indexing.
Indexing with Element Positions
The most common approach is to explicitly specify the indices of the elements. For example, to access a single element of a matrix, specify the row number followed by the column number of the element.
e is the element in the 3,2 position (third row, second column) of A .
You can also reference multiple elements at a time by specifying their indices in a vector. For example, access the first and third elements of the second row of A .
To access elements in a range of rows or columns, use the colon operator. For example, access the elements in the first through third rows and the second through fourth columns of A .
An alternative way to access those elements is to use the keyword end to represent the last column. This approach lets you specify the last column without knowing exactly how many columns are in A .
If you want to access all of the rows or columns, use the colon operator by itself. For example, return the entire third column of A .
In general, you can use indexing to access elements of any array in MATLAB regardless of its data type or dimensions. For example, directly access a column of a datetime array.
For higher-dimensional arrays, expand the syntax to match the array dimensions. Consider a random 3-by-3-by-3 numeric array. Access the element in the second row, third column, and first sheet of the array.
For more information on working with multidimensional arrays, see Multidimensional Arrays .
Indexing with Single Index
Another approach for accessing elements of an array is to use only a single index, regardless of the size or dimensions of the array. This approach is known as linear indexing . While MATLAB displays arrays according to their defined sizes and shapes, they are actually stored in memory as a single column of elements. A good way to visualize this concept is with a matrix. While the following array is displayed as a 3-by-3 matrix, MATLAB stores it as a single column made up of the columns of A appended one after the other. The stored vector contains the sequence of elements 12 , 45 , 33 , 36 , 29 , 25 , 91 , 48 , 11 , and can be displayed using a single colon.
For example, the 3,2 element of A is 25 , and you can access it using the syntax A(3,2) . You can also access this element using the syntax A(6) , since 25 is the sixth element of the stored vector sequence.
While linear indexing can be less intuitive visually, it can be powerful for performing certain computations that are not dependent on the size or shape of the array. For example, you can easily sum all of the elements of A without having to provide a second argument to the sum function.
The sub2ind and ind2sub functions help to convert between original array indices and their linear version. For example, compute the linear index of the 3,2 element of A .
Convert the linear index back to its row and column form.
Indexing with Logical Values
Using true and false logical indicators is another useful approach to index into arrays, particularly when working with conditional statements. For example, suppose you want to know if the elements of a matrix A are less than the corresponding elements of another matrix B . The less-than operator returns a logical array whose elements are 1 where an element in A is smaller than the corresponding element in B .
Now that you know the locations of the elements meeting the condition, you can inspect the individual values using ind as the index array. MATLAB matches the locations of the value 1 in ind to the corresponding elements of A and B , and lists their values in a column vector.
MATLAB " is " functions also return logical arrays that indicate which elements of the input meet a certain condition. For example, check which elements of a string vector are missing using the ismissing function.
Suppose you want to find the values of the elements that are not missing. Use the ~ operator with the index vector ind to do this.
For more examples using logical indexing, see Find Array Elements That Meet Conditions .
Mixed Indexing with Logical Values and Element Positions
You can also use a combination of positional and logical indexing to access array elements.
For example, create a 5-by-5 matrix.
Suppose you want to select the elements of A that are located in rows with prime indices and in columns with indices 2, 3, and 4.
To do this, create a vector B that represents the indices of the rows in A .
Use the isprime function to determine which elements in B are prime. The result is a logical array that you can use to index into the rows of A .
Next, define the columns you want to select, which are located in positions 2 to 4.
Use logical indexing to select the rows of A located at prime number positions, as defined by rows . Then, use indexing by position to select the columns of A ranging from positions 2 to 4, as defined by cols .
Related Topics
- Access Data Using Categorical Arrays
- Access Data in Tables
- Structure Arrays
- Access Data in Cell Array
- Indexed Assignment
External Websites
- Programming: Organizing Data (MathWorks Teaching Resources)
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: .
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)
- 简体中文 Chinese
- 日本 Japanese (日本語)
- 한국 Korean (한국어)
Contact your local office
Browse Course Material
Course info.
- Yossi Farjoun
Departments
- Mathematics
As Taught In
- Programming Languages
- Computational Modeling and Simulation
- Applied Mathematics
Learning Resource Types
Introduction to matlab programming, unit 1 the basics.
Exercise 1 (PDF)
Exercise 2 (PDF)
Exercise 3 (PDF)
Unit 2 Root-Finding
Exercise 4 (PDF)
Exercise 5 (PDF)
Exercise 6 (PDF)
Exercise 7 (PDF)
Exercise 8 (PDF)
Exercise 9 (PDF)
Unit 3 Basic Plotting
Exercise 10 (PDF)
Exercise 11 (PDF)
Unit 4 Vectorization
Exercise 12 (PDF)
Exercise 13 (PDF)
Exercise 14 (PDF)
Exercise 15 (PDF)
Unit 5 Fractals and Chaos
Exercise 16 (PDF)
Exercise 17 (PDF)
Exercise 18 (PDF)
Exercise 19 (PDF)
Unit 6 Debugging
Unit 7 conway game of life.
Exercise 20 (PDF)
Exercise 21 (PDF)
You are leaving MIT OpenCourseWare
- Matlab Tutorial
- MATLAB - Home
- MATLAB - Overview
- MATLAB - Features
- MATLAB - Environment Setup
- MATLAB - Editors
- MATLAB - Online
- MATLAB - Workspace
- MATLAB - Syntax
- MATLAB - Variables
- MATLAB - Commands
- MATLAB - Data Types
- MATLAB - Operators
- MATLAB - Data Type Conversion
- MATLAB - Variable Names
- MATLAB - Dates and Time
- MATLAB - Numbers
- MATLAB - Random Numbers
- MATLAB - Strings and Characters
- MATLAB - Text Formatting
- MATLAB - Timetables
- MATLAB - M-Files
- MATLAB - Colon Notation
- MATLAB - Data Import
- MATLAB - Data Output
- MATLAB - Normalize Data
- MATLAB - Predefined Variables
- MATLAB - Decision Making
- MATLAB - Decisions
- MATLAB - If End Statement
- MATLAB - If Else Statement
- MATLAB - If…Elseif Else Statement
- MATLAB - Nest If Statememt
- MATLAB - Switch Statement
- MATLAB - Nested Switch
- MATLAB - Loops
- MATLAB - For Loop
- MATLAB - While Loop
- MATLAB - Nested Loops
- MATLAB - Break Statement
- MATLAB - Continue Statement
- MATLAB - End Statement
MATLAB - Arrays
- MATLAB - Subarrays
- MATLAB - Vectors
- MATLAB - Transpose Operator
- MATLAB - Array Indexing
- MATLAB - Multi-Dimensional Array
- MATLAB - Compatible Arrays
- MATLAB - Categorical Arrays
- MATLAB - Cell Arrays
- MATLAB - Matrix
- MATLAB - Sparse Matrix
- MATLAB - Tables
- MATLAB - Structures
- MATLAB - Array Multiplication
- MATLAB - Array Division
- MATLAB - Array Functions
- MATLAB - Functions
- MATLAB - Function Arguments
- MATLAB - Anonymous Functions
- MATLAB - Nested Functions
- MATLAB - Return Statement
- MATLAB - Void Function
- MATLAB - Local Functions
- MATLAB - Global Variables
- MATLAB - Function Handles
- MATLAB - Inline Functions
- MATLAB - Filter Function
- MATLAB - Factorial
- MATLAB - Private Functions
- MATLAB - Sub-functions
- MATLAB - Recursive Functions
- MATLAB - Function Precedence Order
- MATLAB - Map Function
- MATLAB - Mean Function
- MATLAB - End Function
- MATLAB - Error Handling
- MATLAB - Try...Catch statement
- MATLAB - Debugging
- MATLAB - Plotting
- MATLAB - Plot Arrays
- MATLAB - Plot Vectors
- MATLAB - Bar Graph
- MATLAB - Histograms
- MATLAB - Graphics
- MATLAB - Generating Sub-Plots
- MATLAB - 2D Line Plot
- MATLAB - 3D Plots
- MATLAB - Formatting a Plot
- MATLAB - Logarithmic Axes Plots
- MATLAB - Plotting Error Bars
- MATLAB - Plot a 3D Contour
- MATLAB - Polar Plots
- MATLAB - Scatter Plots
- MATLAB - Plot Expression or Function
- MATLAB - Draw Rectangle
- MATLAB - Plot Spectrogram
- MATLAB - Plot Mesh Surface
- MATLAB - Plot Sine Wave
- MATLAB - Interpolation
- MATLAB - Linear Interpolation
- MATLAB - 2D Array Interpolation
- MATLAB - 3D Array Interpolation
- MATLAB - Polynomials
- MATLAB - Polynomial Addition
- MATLAB - Polynomial Multiplication
- MATLAB - Polynomial Division
- MATLAB - Derivatives of Polynomials
- MATLAB - Transformation
- MATLAB - Transforms
- MATLAB - Laplace Transform
- MATLAB - Laplacian Filter
- MATLAB - Laplacian of Gaussian Filter
- MATLAB - Inverse Fourier transform
- MATLAB - Fourier Transform
- MATLAB - Fast Fourier Transform
- MATLAB - 2-D Inverse Cosine Transform
- MATLAB - Add Legend to Axes
- MATLAB - Object Oriented
- MATLAB - Object Oriented Programming
- MATLAB - Classes and Object
- MATLAB - Functions Overloading
- MATLAB - Operator Overloading
- MATLAB - User-Defined Classes
- MATLAB - Copy Objects
- MATLAB - Algebra
- MATLAB - Linear Algebra
- MATLAB - Gauss Elimination
- MATLAB - Gauss-Jordan Elimination
- MATLAB - Reduced Row Echelon Form
- MATLAB - Eigenvalues and Eigenvectors
- MATLAB - Integration
- MATLAB - Double Integral
- MATLAB - Trapezoidal Rule
- MATLAB - Trapz
- MATLAB - Simpson's Rule
- MATLAB - Miscellenous
- MATLAB - Calculus
- MATLAB - Differential
- MATLAB - Column Vectors
- MATLAB - Cone Effect
- MATLAB - Glassy Effect
- MATLAB - Image Shading
- MATLAB - Swirl Effect
- MATLAB - Tiling Effect
- MATLAB - Oil Painting
- MATLAB - Cumulative Sum
- MATLAB - Curve Fitting
- MATLAB - Quad and Quadl
- MATLAB - Trigonometric Functions
- MATLAB - Deconvolution
- MATLAB - Inverse of Matrix
- MATLAB - Annotation
- MATLAB - Upsampling
- MATLAB - Lossless Predictive Coding
- MATLAB - Texture Measures from GLCM
- MATLAB - Allocates Memory
- MATLAB - Linearly Spaced Vector
- MATLAB - K-Means Clustering
- MATLAB - Fuzzy C-means Clustering
- MATLAB - GNU Introduction
- MATLAB - GNU Octave
- MATLAB - Simulink
- MATLAB - Symbolic Mathematics
- MATLAB - Limit of Symbolic Expression
- MATLAB - Profiler Tool
- MATLAB - Code Indentation
- MATLAB - Buil-in Functions
- MATLAB - Useful Resources
- MATLAB - Quick Guide
- MATLAB - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays.
Special Arrays in MATLAB
In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array.
The zeros() function creates an array of all zeros −
For example −
MATLAB will execute the above statement and return the following result −
The ones() function creates an array of all ones −
The eye() function creates an identity matrix.
The rand() function creates an array of uniformly distributed random numbers on (0,1) −
A Magic Square
A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally.
The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3.
Multidimensional Arrays
An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix.
Generally to generate a multidimensional array, we first create a two-dimensional array and extend it.
For example, let's create a two-dimensional array a.
The array a is a 3-by-3 array; we can add a third dimension to a , by providing the values like −
We can also create multidimensional arrays using the ones(), zeros() or the rand() functions.
For example,
We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension −
Syntax for the cat() function is −
B is the new array created
A1 , A2 , ... are the arrays to be concatenated
dim is the dimension along which to concatenate the arrays
Create a script file and type the following code into it −
When you run the file, it displays −
Array Functions
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.
The following examples illustrate some of the functions mentioned above.
Length, Dimension and Number of elements −
When you run the file, it displays the following result −
Circular Shifting of the Array Elements −
Sorting Arrays
Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions and data types.
The cell function is used for creating a cell array. Syntax for the cell function is −
C is the cell array;
dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;
dim1, ... , dimN are scalar integers that specify the dimensions of C;
obj is One of the following −
- Java array or object
- .NET array of type System.String or System.Object
Accessing Data in Cell Arrays
There are two ways to refer to the elements of a cell array −
- Enclosing the indices in first bracket (), to refer to sets of cells
- Enclosing the indices in braces {}, to refer to the data within individual cells
When you enclose the indices in first bracket, it refers to the set of cells.
Cell array indices in smooth parentheses refer to sets of cells.
You can also access the contents of cells by indexing with curly braces.
- MATLAB Answers
- File Exchange
- AI Chat Playground
- Discussions
- Communities
- Treasure Hunt
- Community Advisors
- Virtual Badges
You are now following this question
- You will see updates in your followed content feed .
- You may receive emails, depending on your communication preferences .
assigning array to another
Direct link to this question
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another
6 Comments Show 4 older comments Hide 4 older comments
Direct link to this comment
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276411
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276412
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276413
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276414
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276415
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276416
Sign in to comment.
Sign in to answer this question.
Accepted Answer
Direct link to this answer
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#answer_173868
1 Comment Show -1 older comments Hide -1 older comments
https://au.mathworks.com/matlabcentral/answers/195998-assigning-array-to-another#comment_276419
More Answers (0)
Community treasure hunt.
Find the treasures in MATLAB Central and discover how the community can help you!
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
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: .
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)
- 简体中文 Chinese
- 日本 Japanese (日本語)
- 한국 Korean (한국어)
Contact your local office
IMAGES
VIDEO
COMMENTS
Now, I wanna assign the value A(2 10 12)=20 to the same array. But, value of the new array will be the sum of previous if the index matches.
While MATLAB displays arrays according to their defined sizes and shapes, they are actually stored in memory as a single column of elements. A good way to visualize this concept is with a matrix. While the following array is displayed as a 3-by-3 matrix, MATLAB stores it as a single column made up of the columns of A appended one after the other.
However, if they are packed in one variable, you can only deal them if they are in a cell or structure array - with deal(X{:}) for cell array and deal(S.field) for structure array. (In the latter case only one field is dealt, but from all structures in array.) With Matlab v.7+ you can use X{:} and S.field without deal, as noted in other answers.
Introduction To MATLAB Programming. Menu. More Info Syllabus The Basics What is Programming? Command Prompt and Expressions Lists, Vectors, and Matrices Variables Root-Finding Warm-up ... assignment_turned_in Programming Assignments with Examples. Download Course.
An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix. Generally to generate a multidimensional array, we first create a two-dimensional array and extend it. For example, let's create a two-dimensional array a.
http://goo.gl/cDpy6o for more FREE video tutorials covering MATLAB ProgrammingThis video gives a brief overview on array assignment which is an important par...
Extract value(s) from an array variable in MATLAB (using indices) 6) Modify existing array variables in MATLAB, assign specific section(s) of an array variable. 7) Operate on array variables in MATLAB correctly. 8) Manipulate arrays in MATLAB to solve engineering problems. EXERCISES: Part A: Complete the following activities before lecture: 1)
It'd be nice if Matlab syntax allowed expanding arrays into an argument sequence, something like '{values}{:}'. Tried making a function to take a cell value list, but apparently it does not like assigning to varargout in the exact same way that deal() does haha.
assigning array to another. Learn more about matrix . First I have Matrix A which is 1125 X 30 dimensions. I want to initialize Matrix B as 10 X 30, first as zeros and then matrix B takes the first ninth rows of matrix A, and keep its last rows as zeros.
3 Two-Dimensional arrays: Matrices A 1D array has a single index to specify the location of the elements within the array. A two-dimensional (2D) array uses two indices to specify the location of its elements. In linear algebra, a 2D array is called a matrix. The elements of a matrix are displayed in a two-dimensional table form.