当前位置: 代码迷 >> 其他开发语言 >> reshape函数出现有关问题
  详细解决方案

reshape函数出现有关问题

热度:937   发布时间:2016-05-02 04:13:17.0
求助 reshape函数出现问题

大家好,我刚刚接触Matlab,有一段代码交给我调试,可是在运行到reshape函数的时候报错:“Error using reshape
 To RESHAPE the number of elements must not change.”我在网上查,说是因为矩阵的大小在转换前后改变了。但是我又瞧不出来哪里改变了,请大家帮忙看一下啊,我读代码感觉这段程序的作用就是将三个文件的内容分别读入三个矩阵,然后再转置一下这三个矩阵,然后再合并这三个矩阵,然后将这个合并后的矩阵内容返回到一个三维数组之中。代码如下:
 
……
 yr=38;np_chn=545;lat1=73;lon1=144;nf=3;np=20;
 ……
 fdir2='E:\data\ncep\gh\gh500\gh_71_08\global\';
 fid2=fopen([fdir2,'gh_an_may_71.1_08.7.dat'],'r'); %Model
 gh1=fread(fid2,[lat1*lon1 yr],'float32');
 fid3=fopen([fdir2,'gh_an_jun_71.1_08.7.dat'],'r'); %Model
 gh2=fread(fid3,[lat1*lon1 yr],'float32');
 fid4=fopen([fdir2,'gh_an_jul_71.1_08.7.dat'],'r'); %Model
 gh3=fread(fid4,[lat1*lon1 yr],'float32');
 
gh1=permute(gh1,[2 1]); %[yr lat1*lon1]
 gh2=permute(gh2,[2 1]);
 gh3=permute(gh3,[2 1]);
 
fa_thr=cat(2,gh1,gh2,gh3);
 fa_thr=reshape(fa_thr,[yr lat1*lon1 nf]); %[yr lat1*lon1 nf]
 ……
 
错误提示是:
 Error using reshape
 To RESHAPE the number of elements must not change.
 Error in choose_fathr_grid (line 105)
 fa_thr=reshape(fa_thr,[yr lat1*lon1 nf]); %[yr lat1*lon1 nf]
 
请大家帮我看一下,是哪里的错误啊,怎么解决,很急,请大家多多帮助,谢谢!
 





------解决方案--------------------
reshape前后元素个数必须相等.这是错误的原因.下面是分析

先看官方说明
reshape(A,m,n) returns the m-by-n matrix B whose elements are taken column-wise from A. An error results if A does not have m*n elements.

再分析你的语句reshape(fa_thr,[yr lat1*lon1 nf])

fa_thr = cat(2,gh1,gh2,gh3);将gh1,gh2,gh3转置后当做列向量排在一起,也就是fa_thr = [gh1,gh2,gh3],其中3个gh都是[lat1*lon1 yr]的矩阵,那么转置后fa_thr的size就是[yr 3*lat1*lon1],共有元素: yr*lat1*lon1*3 = 38*73*144*3 = 1198368

而reshape后你指定的size=[yr lat1*lon1 nf],共有元素: yr*lat1*lon1*nf = 38*73*144*3 = 1198368

从你贴出来的部分来看,没有任何问题,我也测试过代码,的确没有问题,reshape成功的.猜测原因:
你的代码中间(reshape之前)某个地方修改了尺寸参数的某一个(yr=38;np_chn=545;lat1=73;lon1=144;nf=3;np=20;),导致2个reshape的矩阵和你指定的size元素个数不相等,这也是报错提示的问题.

ps.一个小问题就是permute(A,[2,1])其实就是A.',转置而已,为什么不用简单的写法,非要permute,不解