Clear Filters
Clear Filters

To RESHAPE number of elements must not change

30 views (last 30 days)
Sahana
Sahana on 16 Aug 2024 at 19:14
Answered: Star Strider on 16 Aug 2024 at 19:29
Hi all, im trying to do simple ERP study using EEGLAB. To RESHAPE number of elements must not change, such an error messahe was thrown. let me know how to fix it. Thanks

Answers (3)

John D'Errico
John D'Errico on 16 Aug 2024 at 19:18
Edited: John D'Errico on 16 Aug 2024 at 19:28
How do you fix it? Make sure you know what the size of your array is, before doing a reshape. This way when you do that reshape operation, you won't be surprised.
Exactly what should MATLAB do for this case:
x = 1:5;
reshape(x,2,3)
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.
that error message tells you that you are trying to stuff something into a container of the wrong size. In this example, if you try to turn 5 elements into 6 elements, MATLAB tells you there is a problem, and that problem is yours to resolve. All MATLAB can know is you did something wrong.
And don't tell me that MATLAB should just know to pad the array with zeros if necessary, or delete elements if too many are provided. There will be others who will equally vociferously shout that MATLAB should be smart enough to resample the data over a longer or shorter range as needed.
In general, the way to fix it is to just follow good coding practice. Know what you are working with. Know what you are doing to it.

Torsten
Torsten on 16 Aug 2024 at 19:18
Edited: Torsten on 16 Aug 2024 at 19:20
It means that the number of elements in the original and the reshaped array must be the same:
a = rand(15,1);
a_ok = reshape(a,3,5) % 3*5 = 15
a_ok = 3x5
0.2179 0.1061 0.2989 0.4054 0.6724 0.3301 0.3869 0.1011 0.2575 0.7953 0.7887 0.4166 0.6117 0.5548 0.7120
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
a_not_ok = reshape(a,3,4) % 3*4 = 12 ~= 15
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.

Star Strider
Star Strider on 16 Aug 2024 at 19:29
An alternative to reshape that you may want to use instead is the Signal Processing Toolbox buffer function. With a vector input, the output is a matrix. In order to make it work as a matrix, the unfilled elements in the last column of the output matrix are zero, so consider that.

Community Treasure Hunt

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

Start Hunting!