-1

In MATLAB I can easily get a vector of the elements of a matrix in column major order using the (:) operator as follows...

EDU>> A

A =

     1     2
     3     4
     5     6

EDU>> A(:)

ans =

     1
     3
     5
     2
     4
     6

However, I would like to get a vector of the elements in row major order. So i figured I would transpose the matrix before using (:). But I get this error...

EDU>> A'(:)
 A'(:)
  |
Error: Unbalanced or unexpected parenthesis or bracket.

Why won't ' and (:) compose here? I can do it in 2 steps but I would prefer to be more concise and avoid the extra variable.

EDU>> B = A'

B =

     1     3     5
     2     4     6

EDU>> B(:)

ans =

     1
     2
     3
     4
     5
     6

Why can't I do this in 1 step by composing ' and (:)? What is the right way to do this?

Thanks, ~chuck

Chuck
  • 1,850
  • 2
  • 17
  • 28
  • 5
    This is basically a duplicate of [this question](http://stackoverflow.com/q/2724020/52738). Also, [this related question](http://stackoverflow.com/q/3627107/52738) addresses further how the indexing operator `()` can't follow certain operations, unless you turn it into a function call. – gnovice May 02 '13 at 17:46
  • Thanks, my primary question was really about the 2nd point concerning the indexing operator. Interestingly, Octave doesn't seem to suffer from this issue. – Chuck May 02 '13 at 18:18

1 Answers1

4

Using reshape perhaps

reshape(A',prod(size(A)),1)
Shijing Lv
  • 6,286
  • 1
  • 20
  • 12
  • what's wrong with this? – Shijing Lv May 02 '13 at 18:57
  • 2
    Seems ok to me. Sorry somebody voted you down. – Chuck May 02 '13 at 19:00
  • I am going to delete my post, which was the same as yours but earlier. somebody around is not happy. If the answer is not exactly what they want, why should they easily give people a downvote. – NKN May 02 '13 at 19:08
  • 3
    +1 for the `reshape`, but it's better to go for the shorter `reshape(A', [], 1)` and let `reshape` calculate the number of elements in `A`. If you insist on doing that by yourself, consider using `numel(A)` instead of `prod(size(A))`. – Eitan T May 02 '13 at 21:35