如何在Matlab中使用重塑? [英] How to use reshape in Matlab?

查看:72
本文介绍了如何在Matlab中使用重塑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过imagesize * 1(列向量)重塑像素强度.

I want to reshape pixel intensity by imagesize*1(column vector).

Imvect = reshape(I,imsize,1);

但是为什么会出现这些错误?

But why these error comes?

Error using reshape
To RESHAPE the number of elements must not change.

推荐答案

让我们从文档:

B = reshape(A,sz1,...,szN)

reshape的作用是获取矩阵A,将其弄直,然后为其赋予新的大小,该大小由第2个,第3个至第N个参数确定.为此,输入矩阵中的元素数必须与输出矩阵中的元素数相同.您不能将1x5向量变成2x3向量,因为缺少一个元素.输出矩阵中的元素数量将与sz1, sz2, ..., szN的乘积成比例.现在,如果您知道要N行,但是不知道确切有多少列,则可以使用[]语法,该语法告诉MATLAB使用尽可能多的列以使元素数相等.

What reshape does is to take the matrix A, straightens it out, and gives it a new size, that's determined by the 2nd, 3rd to the Nth argument. For this to be possible, you need to have the same number of elements in the input matrix as you have in the output matrix. You can't make a 1x5 vector turn into a 2x3 vector, as one element would be missing. The number of elements in the output matrix will be proportional to the product of sz1, sz2, ..., szN. Now, if you know you want N rows, but don't know exactly how many columns you have, you might use the [] syntax, that tells MATLAB to use as many columns as necessary to make the number of elements be equal.

因此reshape(A, 2, [], 3)将成为2xNx3矩阵,其中,对于具有24个元素的矩阵,N将为4.

So reshape(A, 2, [], 3) will become a 2xNx3 matrix, where, for a matrix with 24 elements, N will be 4.

现在,情况并非如此. numel(I) ~= imsize.如果mod(numel(I), imsize) ~= 0,则您的imsize绝对不正确.但是,如果使用mod(numel(I), imsize) == 0,那么您的错误可能是您希望imsize的行数和列数使之成为可能.如果是后者,则应该可以:

Now, in your case this is not the case. numel(I) ~= imsize. If mod(numel(I), imsize) ~= 0 then your imsize is definitely incorrect. However, if mod(numel(I), imsize) == 0, then your error might be that you want imsize number of rows, and a number of columns that makes this possible. If it's the latter, then this should work:

Imvect = reshape(I,imsize, []);

如果只想让矩阵I为大小为(numel(I), 1)的向量,则应使用

If you simply want to make you matrix I a vector of size (numel(I), 1), then you should use the colon operator :, as such:

Imvect = I(:);

如果您真的想使用reshape,另一种选择是指定您只需要一列,然后让MATLAB选择行数,如下所示:

An alternative, if you really want to use reshape, is to specify that you want a single column, and let MATLAB select the number of rows, as such:

Imvect = reshape(I, [], 1);

这篇关于如何在Matlab中使用重塑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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