Error using reshape Number of elements must not change. Use [] as one of the size inputs to automatically calculate the appropriate size for that dimension.

조회 수: 8 (최근 30일)
Hi,
I have the following code inside of a function:
x = exp(xi);
sz = size(x, 1)-255;
a = reshape(x(1:sz-1,:), [255 256]);
b = x(sz:end, :);
I am using a minimisation function on this function which throws the following error.
Error using reshape
Number of elements must not change. Use [] as one of the size inputs to automatically calculate the appropriate
size for that dimension.
Error in minimize (line 75)
[f0 df0] = feval(f, X, varargin{:}); % get function value and gradient
I would appreciate any ideas as to why this error might be occuring. Thanks! :)

답변 (1개)

Walter Roberson
Walter Roberson 2022년 3월 1일
sz = size(x, 1)-255;
a = reshape(x(1:sz-1,:), [255 256]);
So x(1:sz-1,:) would get all except the last 256 rows of x . And then you reshape that to 255 by 256. that is only going to work if the original data was 511 x 256 or certain other "magic" size combinations.
The reason to use things like size(x,1) are to permit flexibility in the size of the array x. But your reshape() is coded in a way that provides no flexibility: it demands that the data be exactly a certain number of elements, which contradicts the request for general size handling gained by asking size()
  댓글 수: 4
Emilia Butters
Emilia Butters 2022년 3월 1일
Ah okay thanks! I've fixed it to the following but it still throws the reshape error...
theta_unlog = exp(theta);
sz = size(theta_unlog, 1);
new_sz = sz-256;
new_theta = theta_unlog(1:new_sz,:);
a = reshape(new_theta, [255 256]);
b = theta_unlog(new_sz+1:end, :);
Walter Roberson
Walter Roberson 2022년 3월 2일
If you want the remaining to have 255*256 elements after you took away 256 then it follows that the original should have 255*256 + 1*256 = 256*256 elements, which is 65536

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by