当前位置: 动力学知识库 > 问答 > 编程问答 >

matlab - In what order will the matrix C be returned if you call it like C(:)

问题描述:

I have called C(:) for the following matrix:

[0 0 1]

[1 1 0]

[0 1 0]

and the output I get is: [0 1 0 0 1 1 1 0 0], i.e. it returns the matrix from the very last entry moving right to left to the very first entry.

Other times it returns the array that includes entries from top left, moving left to right to the very last entry. And sometimes it just returns something unknown.

I have tried using C(:) on

[0 1 1]

[1 0 1]

[0 0 0]

and I get: [0 1 0 1 0 0 1 1 0]. How can I get it to consistently return the entries starting from the top left entry moving left to right, to the very last one?

网友答案:

There are no inconsistencies about C(:) at all. It behaves the same regardless of what matrix you use when you call it this way. C(:) unwraps the matrix so that it's stacked in column-major format. This means that all of the columns of the matrix are stacked on top of each other to produce a single column:

>> C = [1 2 3; 4 5 6; 7 8 9]

C =

     1     2     3
     4     5     6
     7     8     9

>> C(:)

ans =

     1
     4
     7
     2
     5
     8
     3
     6
     9

If you want to unwrap row-wise, you must transpose the matrix first. This way, all rows become columns and vice-versa, and so when you stack the columns in column-major order, the rows are now the columns, thus completing what you want:

>> C = [1 2 3; 4 5 6; 7 8 9]

C =

     1     2     3
     4     5     6
     7     8     9

>> C = C.'

C =

     1     4     7
     2     5     8
     3     6     9

>> C(:)

ans =

     1
     2
     3
     4
     5
     6
     7
     8
     9
网友答案:

Is this MATLAB/Octave? If so, as far as I know, it's relative to the dimension number. For example, in a 2D matrix, the first dimension are the lines, second dimension are the columns.

So, using the (:) operator will do the following:

octave:1> x = magic(3)
x =

   8   1   6
   3   5   7
   4   9   2

octave:2> x(:)
ans =

   8
   3
   4
   1
   5
   9
   6
   7
   2

If you want it the other way around, just transpose the matrix beforehand:

octave:3> x'(:)
ans =

   8
   1
   6
   3
   5
   7
   4
   9
   2
分享给朋友:
您可能感兴趣的文章:
随机阅读: