Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

How do I resize a matrix in MATLAB?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...