Message Boards Message Boards

1
|
15260 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Indexing an array in Mathematica

Posted 9 years ago

I would like to select out specific elements of an array (two dimensional) in order to operate on them. What is the proper syntax for indexing through an array in Mathematica (specifying both dimensions)?

POSTED BY: Patrick Shannon
2 Replies

If you have a 2D array and want to slice out part to operate on, you can use the ;; notation in the array indices. For example, given a 3x4 array you can extract the 2x2 subarray for rows 2-3, columns 3-4 as follows.

In[1]:= a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}

Out[1]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}

In[2]:= a[[2 ;; 3, 3 ;; 4]]

Out[2]= {{7, 8}, {11, 12}}

You can use the same notation to then modify that region of the array:

In[3]:= a[[2 ;; 3, 3 ;; 4]] = {{-1, -2}, {-3, -4}}

Out[3]= {{-1, -2}, {-3, -4}}

In[4]:= a

Out[4]= {{1, 2, 3, 4}, {5, 6, -1, -2}, {9, 10, -3, -4}}
POSTED BY: Matthew Sottile

The function is Part

http://reference.wolfram.com/language/ref/Part.html?q=Part

A small example:

In[3]:= anArray = {{1, 2, 3, 4}, {5, 6, 7, 8}}

Out[3]= {{1, 2, 3, 4}, {5, 6, 7, 8}}

In[5]:= anArray[[2, 3]]

Out[5]= 7

In[6]:= anArray[[2, 3]] = "Happy"

Out[6]= "Happy"

In[7]:= anArray

Out[7]= {{1, 2, 3, 4}, {5, 6, "Happy", 8}}
POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract