Reshape Array after Padding/Truncating Mismatching Dimension

Use reshape function without worrying about dimension sizes, choose either to truncate your vector or pad it to match the desired dimensions
15 Downloads
Updated Tue, 23 Feb 2021 11:45:29 +0000

View License

B = reshape0(A,sz,method,padWithWhat) reshapes A using the size vector, sz, to define size(B). For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements. if prod(sz) is not the same as numel(A), this function will either truncate or pad the input.

example
B = reshape0(A,[sz1,sz2,...,szN]) reshapes A into a sz1-by-...-by-szN array where sz1,...,szN indicates the size of each dimension. You can specify a single dimension size of -1 to have the dimension size automatically calculated, such that the number of elements in B matches the number of elements in A. For example, if A is a 10-by-10 matrix, then reshape0(A,[2,2,-1]) reshapes the 100 elements of A into a 2-by-2-by-25 array.
If prod(sz) is not the same as numel(A), this function with either truncate or pad (default) the input to match. For example is [A, padSize] = 1:21 (1x21 array), then B = reshape(A,[-1,5],'truncate') will truncate padSize elements and reshape the array into a 4x5 array. And B = reshape(A,[-1,5],'pad') will pad array with padSize elements and reshape the array into a 5x5 array.
You can define with what to pad the array, for example, if A = false(4,5), then [B,padSize] = reshape0(A,[-1,7],'pad',true) will pad A with true(padSize,1) and reshape the array into a 3x7 array.

Cite As

ytzhak goussha (2024). Reshape Array after Padding/Truncating Mismatching Dimension (https://www.mathworks.com/matlabcentral/fileexchange/87724-reshape-array-after-padding-truncating-mismatching-dimension), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2020a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.0.1

Fixed a typo in the title

1.0.0