How can a single matrix element be accessed in Matlab / Octave?

18,219

See the index expressions section of the manual. To get the i'th element from second column:

X(i,2)      # element 'i' from column 2
X(1:end,2)  # the whole 2nd column
X(:,2)      # same thing but shorter
x(:, [2 3]) # whole 2nd and 3rd column

Note that Octave is a language where array elements are in column-major order.

Share:
18,219
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    Suppose I have:

    >> X = magic(5)
    X =
    
       17   24    1    8   15
       23    5    7   14   16
        4    6   13   20   22
       10   12   19   21    3
       11   18   25    2    9
    

    How do I get i'th element from the second column?

    I already figured that indices in (some?) collections in Octave are one-based, but I'm not sure if that holds for matrices, too.

  • carandraug
    carandraug over 11 years
    @wvxvw Whitespace is irrelevant. Think of the indexing as passing arguments to a function, each argument being a matrix. [2 3] is a vector, 1:5 is also a vector (range), 1:end is also just a range it simply interprets end as the last one. You can do 1:2:end for every two, just as you can with simple ranges.
  • carandraug
    carandraug over 11 years
    @wvxvw give it a try. You already have Octave installed. Does it return the same result?
  • carandraug
    carandraug over 11 years
    @wvxvw It is intended. The : is only used for ranges and selecting whole rows and columns in Octave, it's all the same. About the nickname, I automatically get a notification when commenting on my answer so no need.