How do I resize a matrix in MATLAB?

How do I resize a matrix in MATLAB?

滥情空心 发布于 2021-11-27 字数 334 浏览 732 回复 3 原文

Suppose I had a 1-by-12 matrix and I wanted to resize it to a 4-by-3 matrix. How could I do this?

My current solution is kind of ugly:

for n = 1:(length(mat)/3)
    out(n,1:3) = mat( ((n-1)*3 + 1):((n-1)*3 + 3) );
end

Is there a better way to do this?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光是把杀猪刀 2022-06-07 3 楼

to extend gnovice's solution:

If you need a different order of matrix construction, use transpose (the ' operator) or permute() to change the dimension ordering after you have called reshape().

稀香 2022-06-07 2 楼

Try the RESHAPE function:

A = (1-by-12 matrix);
B = reshape(A,4,3);

Note that the matrix B will be filled with elements from A in a columnwise fashion (i.e. columns will be filled from top to bottom, moving left to right).

Example:

>> A = 1:12;
>> B = reshape(A,4,3)

B =

     1     5     9
     2     6    10
     3     7    11
     4     8    12
听不够的曲调 2022-06-07 1 楼

reshape is of course the proper solution, as stated by @gnovice.

A nice feature of reshape is that it allows this:

A = 1:12;
B = reshape(A,4,[]);
B =
     1     5     9
     2     6    10
     3     7    11
     4     8    12

So if you don't know how many columns there will be, reshape will compute it for you. Likewise, reshape will fill in the number of rows, if you leave that out.

C = reshape(A,[],4)
C =
     1     4     7    10
     2     5     8    11
     3     6     9    12