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' '' '' ?
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:
You can achieve the desired result by:
'') to match the maximum length.
% 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);
The result will be:
'a' 'd' 'e'
'b' '' 'f'
'c' '' ''
cellfun with @numel to determine the number of elements in each vector and get the maximum.'') to make its length equal to the maximum.[ ... ]) to combine the padded vectors.This approach works for any number of input vectors and handles variable lengths seamlessly.