Question
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' '' '' ?
Related Questions
Expert Answer
John Michell
PhD Expert
Answered Aug 14, 2026
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:
- Determining the maximum length of the input vectors.
- Padding shorter vectors with empty strings (
'') to match the maximum length. - 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
- Find Maximum Length: Use
cellfunwith@numelto determine the number of elements in each vector and get the maximum. - Pad with Empty Strings: For each vector, append enough empty strings (
'') to make its length equal to the maximum. - Concatenate Horizontally: Use horizontal concatenation (
[ ... ]) to combine the padded vectors.
This approach works for any number of input vectors and handles variable lengths seamlessly.
Have a different question? Ask here