How to concatenate string vectors of unequal length?

Illustration
Hazel - 2020-11-30T10:29:20+00:00
Question: How to concatenate string vectors of unequal length?

If I have thee vectors v1 = {'a' 'b' 'c'}', v2 = {'d'}' and v3 = {'e' 'f'}', how do I create a four vector v4 = 'a' 'd' 'e' 'b' '' 'f' 'c' '' '' ?

Expert Answer

Profile picture of John Michell John Michell answered . 2025-11-20

To concatenate string vectors of unequal lengths into a single matrix in MATLAB, you can use padding to ensure all vectors have the same number of elements. Here’s how you can achieve this:

Solution

You can achieve the desired result by:

  1. Determining the maximum length of the input vectors.
  2. Padding shorter vectors with empty strings ('') to match the maximum length.
  3. Concatenating the vectors into a matrix.

Code Example:

 

% Input vectors
v1 = {'a'; 'b'; 'c'};
v2 = {'d'};
v3 = {'e'; 'f'};

% Combine the vectors into a cell array
vectors = {v1, v2, v3};

% Find the maximum length of the vectors
max_length = max(cellfun(@numel, vectors));

% Pad each vector with empty strings to match the maximum length
padded_vectors = cellfun(@(v) [v; repmat({''}, max_length - numel(v), 1)], ...
                         vectors, 'UniformOutput', false);

% Concatenate the padded vectors horizontally
v4 = [padded_vectors{:}];

% Display the result
disp(v4);

Output

The result will be:

 

    'a'    'd'    'e'
    'b'    ''     'f'
    'c'    ''     ''

Explanation

  1. Find Maximum Length: Use cellfun with @numel to determine the number of elements in each vector and get the maximum.
  2. Pad with Empty Strings: For each vector, append enough empty strings ('') to make its length equal to the maximum.
  3. Concatenate Horizontally: Use horizontal concatenation ([ ... ]) to combine the padded vectors.

This approach works for any number of input vectors and handles variable lengths seamlessly.


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!