1

The following example appears in the MATLAB tutorial:

X = [16  2 13;
     5  11  8;
     9   7 12;
     4  14  1]

Using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So:

X(2:2:10) = []

results in:

X = [16 9 2 7 13 12 1]

Mysteriously, the entire 2nd row and the first two elements in the 4th row have been deleted, but I can't see the correspondence between the position of the deleted elements and the index vector 2:2:10. Can someone please explain?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Dónal
  • 185,044
  • 174
  • 569
  • 824
  • Oops! I probably gave you more info than you needed, since I thought you were asking about the linear-indexing part, not the vector-creation part. Either way, happy to help! =)... and sorry about that jackass 2pac littering your question. – gnovice Feb 21 '09 at 03:28

2 Answers2

12

The example you gave shows linear indexing. When you have a multidimensional array and you give it a single scalar or vector, it indexes along each column from top to bottom and left to right. Here's an example of indexing into each dimension:

mat = [1 4 7; ...
       2 5 8; ...
       3 6 9];
submat = mat(1:2, 1:2);

submat will contain the top left corner of the matrix: [1 4; 2 5]. This is because the first 1:2 in the subindex accesses the first dimension (rows) and the second 1:2 accesses the second dimension (columns), extracting a 2-by-2 square. If you don't supply an index for each dimension, separated by commas, but instead just one index, MATLAB will index into the matrix as though it were one big column vector:

submat = mat(3, 3);     % "Normal" indexing: extracts element "9"
submat = mat(9);        % Linear indexing: also extracts element "9"
submat = mat([1 5 6]);  % Extracts elements "1", "5", and "6"

See the MATLAB documentation for more detail.

gnovice
  • 125,304
  • 15
  • 256
  • 359
  • In that case, surely only the elements at positions 2 and 10 should have been deleted, but it appears 5 elements have been deleted – Dónal Feb 21 '09 at 03:03
  • 1
    2:2:10 create a vector, starting at the number 2 and moving in steps of 2 until the number 10. – gnovice Feb 21 '09 at 03:18
  • great, the vector creation part is what I wasn't "getting" – Dónal Feb 21 '09 at 03:24
0

It's very simple.

It basically starts from the second element in this example and goes upto tenth element (column wise) in steps of 2 and deletes corresponding elements. The remaining elements result in a row vector.

ams
  • 1