如何将矩阵的元素转换为单个向量 [英] How to convert the elements of a matrix into a single vector

查看:156
本文介绍了如何将矩阵的元素转换为单个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的矩阵如下:

A= 1 2
   3 4
   5 6
   7 8

我想以这种方式排列该矩阵的元素,使其产生以下输出:

I want to arrange the elements of this matrix in such a way that it will give me the following output:

B= 1
   2
   3
   4
   5
   6
   7
   8

任何建议都将有所帮助.谢谢!

Any kind of suggestion will be helpful. Thanks!

推荐答案

进行A的转置并将其展开为向量:

Take the transpose of A and unroll it into a vector:

B = A.';
B = B(:);

或者,您可以使用 reshape :

Alternatively, you can use reshape:

B = reshape(A.', [], 1);

首先转置矩阵A的原因是因为MATLAB以 column-major 格式进行展开,这意味着首先要遍历列.您尝试逐行执行此操作,因此需要对输入进行转置以达到相同的效果.

The reason why you transpose the matrix A first is because MATLAB does the unrolling in column-major format, which means that the columns are traversed first. You are trying to do this row-wise, and so you'd need to transpose the input to achieve the same effect.

这是输出的样子(两者都使用):

Here's what the output looks like (using both):

>> A= [1 2
   3 4
   5 6
   7 8];
>> B = A.';
>> B = B(:);
>> B

B =

     1
     2
     3
     4
     5
     6
     7
     8

也:

>> A= [1 2
3 4
5 6
7 8];
>> B = reshape(A.', [], 1)

B =

     1
     2
     3
     4
     5
     6
     7
     8

这篇关于如何将矩阵的元素转换为单个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆