[TOC]

reshape

Reshape array

Basic Idea

When an array (say, a) is reshaped, it is first converted to a vector by indexing all of its elements linearly, i.e., a(1:numel(a)). Then, this vector is rearranged to form an array of the desired size. The number of elements after reshaping remains the same.

For example, the array below is reshaped to an array. reshape

Usage

reshape(A, sizeVec)

reshape(A, s1, s2, ..., sn)

Examples

Input
% 24 elemenets before reshaping
r1 = rand(3,4,2)
% 24 element after reshaping
r2 = reshape(r1,8,3)
Output
r1(:, :, 1) = 1e-1 ×
 9.7679   6.0583   6.3534   9.5830
 2.7812   2.4721   2.5032   2.5139
 3.9738   6.1257   1.0086   0.9723

r1(:, :, 2) = 1e-1 ×
 3.2380   4.9974   6.0711   7.8545
 4.8453   5.1516   6.4629   1.4396
 1.5734   9.0568   9.7506   2.7975

r2 = 1e-1 × 
 9.7679   1.0086   5.1516
 2.7812   9.5830   9.0568
 3.9738   2.5139   6.0711
 6.0583   0.9723   6.4629
 2.4721   3.2380   9.7506
 6.1257   4.8453   7.8545
 6.3534   1.5734   1.4396
 2.5032   4.9974   2.7975
Input
% 12 elements in r1
r1 = rand(3,4)

% 1st dim's length of r2 calculated automatically
r2 = reshape(r1,[],3)
Output
r1 = 1e-1 × 
 6.0433   4.9525   7.5725   5.5289
 9.4648   5.7737   9.4426   8.4097
 5.8870   3.3192   3.1616   6.8046

r2 = 1e-1 × 
 6.0433   5.7737   3.1616
 9.4648   3.3192   5.5289
 5.8870   7.5725   8.4097
 4.9525   9.4426   6.8046