matlab中怎样将一维数组转化为二维矩阵
推荐于2017-11-26 · 知道合伙人软件行家
你可以使用reshape函数进行处理。
例子如下:
A = 1:10;
B = reshape(A,[5,2])
该命令具体的用法可以用下面命令来查看:
doc reshape
下面是Matlab里面关于这个命令的解释:
B = reshape(A,sz) reshapes A using the size vector, sz, to define size(B). For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements, and prod(sz) must be the same as numel(A).
B = reshape(A,sz1,...,szN) reshapes A into a sz1-by-...-by-szN array where sz1,...,szN indicates the size of each dimension. You can specify a single dimension size of[] to have the dimension size automatically calculated, such that the number of elements in B matches the number of elements in A. For example, if A is a 10-by-10 matrix, thenreshape(A,2,2,[]) reshapes the 100 elements of A into a 2-by-2-by-25 array.
下面是关于上面那个例子的解释:
Reshape a 1-by-10 vector into a 5-by-2 matrix.
A = 1:10;
B = reshape(A,[5,2])
B =
1 6
2 7
3 8
4 9
5 10
可以用reshap(),也可以直接“捋直”了。
为了清晰点,给你举个例子吧:
a=[1,2;3,4;];
b=a(:);
c=reshape(a,[],1);
得到的b,c都是一样的一维列向量。
reshape介绍:
reshape函数重新调整矩阵的行数、列数、维数。在matlab命令窗口中键入docreshape或helpreshape即可获得该函数的帮助信息。
用法:
B = reshape(A,m,n)
B = reshape(A,m,n,p,...)
B = reshape(A,[m n p ...])
B = reshape(A,...,[ ],...)
B = reshape(A,siz)
程序示例:
close all; clear; clc;
A = [1 2 3; 4 5 6; 7 8 9; 10 11 12] % 4 by 3
B = reshape(A, 2, 6) % 2 by 6
% C = reshape(A, 2, 4) % error
% D = reshape(A, 2, 10) % error
E = reshape(A, 2, 3, 2) % 2 by 3 by 2
注意:reshape函数对原数组的抽取是按照列抽取的(对原数组按列抽取,抽取的元素填充为新数组的列)