vec2mat

(Not recommended) Change dimension

vec2mat is not recommended. Use reshape instead. For more information, see Compatibility Considerations.

Description

mat = vec2mat(vec,matcol) converts vector vec to matrix mat with matcol columns. The function creates the matrix one row at a time, filling the rows with elements from vec in order. If the length of vec is not a multiple of matcol, then the function pads the last row of mat with zeros until the row contains matcol elements.

mat = vec2mat(vec,matcol,padding) specifies values for the function to use to pad the last row of mat. The function uses the value from padding in order.

example

[mat,padded] = vec2mat(___) also returns padded, the number of padded elements in the last row of mat. You can specify any of the input argument combinations from previous syntaxes.

Examples

collapse all

This example uses shows you how to add padding, as needed, when converting a vector to matrix.

Create a vector that will be converted to a matrix and a vector to provide padding values.

vec = [10;20;30;40;50];
padding = [1,2;3,4;5,6];
n = 4;

When using vec2mat to convert the vector to a matrix, the function determines needed padding.

[mat4,numPadded4] = vec2mat(vec,n,padding)
mat4 =
    10    20    30    40
    50     1     3     5
numPadded4 =
     3

When using reshape to convert the vector to a matrix, the needed padding must be computed and appended to the vector before converting the vector to a matrix.

numPadded = mod(numel(vec),n);
if numPadded > 0
    numPadded = n - numPadded
    mat = reshape([vec.' padding(1:numPadded)], n, []).'
else
    numPadded % No padding required
    mat = reshape(vec.', n, []).'
end
numPadded =
     3
mat =
    10    20    30    40
    50     1     3     5

Input Arguments

collapse all

Input array, specified as a vector.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical
Complex Number Support: Yes

Number of columns for the output matrix mat, specified as a positive integer. If the length of vec is not a multiple of matcol, then the function pads the last row of mat with zeros until the row contains matcol elements.

Data Types: double

Padding values for the last row of mat, specified as a vector or matrix. The padding input inherits the data type of the vec input. The function uses the values from padding in order. If padding has fewer elements than what the function needs to complete the last row of mat, then the function repeats the last element of padding until mat is full.

Output Arguments

collapse all

Output array, returned as a matrix with elements from vec and having matcol columns. The output inherits the data type of the input. The number of rows is equal to ceil(length(vec)/matcol).

Number of padded elements in the last row of mat, returned as a positive integer.

Compatibility Considerations

expand all

Not recommended starting in R2020a

See Also

Introduced before R2006a