How to concatenate string vectors of unequal length?

조회 수: 12 (최근 30일)
Danny
Danny 2014년 12월 20일
편집: Stephen23 2015년 1월 2일
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' '' ''
?
  댓글 수: 1
Stephen23
Stephen23 2014년 12월 21일
편집: Stephen23 2015년 1월 2일
Actually this is concatenating cell arrays of unequal lengths... the fact that these contain strings is totally irrelevant to both the question and the answer. The title should be "How to concatenate cell vectors of unequal length?"

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2014년 12월 20일
Try this:
% Define component cell arrays.
v1 = {'a'; 'b'; 'c'}
v2 = {'d'}
v3 = {'e'; 'f'}
% Find out how big cell array needs to be.
lv1 = length(v1);
lv2 = length(v2);
lv3 = length(v3);
rows = max([lv1,lv2,lv3])
% Instatiate cell array of the max size.
v4 = cell(rows, 3)
% stuff each column in.
v4(1:lv1, 1) = v1;
v4(1:lv2, 2) = v2;
v4(1:lv3, 3) = v3;
% Print out results
fprintf('\n\nHere is the output cell array:\n');
v4
In the command window:
Here is the output cell array:
v4 =
'a' 'd' 'e'
'b' [] 'f'
'c' [] []

추가 답변 (3개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 12월 20일
v1 = {'a' 'b' 'c'}',
v2 = {'d'}'
v3 = {'e' 'f'}'
v=cell(3,3)
v(:,:)={' '}
v(1:3,1)=v1
v(1,2)=v2
v(1:2,3)=v3

Thorsten
Thorsten 2014년 12월 20일
v1 = {'a' 'b' 'c'}';
v2 = {'d'}';
v3 = {'e' 'f'}';
m = max([numel(v1) numel(v2) numel(v3)]);
if numel(v1) < m, v1{m} = []; end
if numel(v2) < m, v2{m} = []; end
if numel(v3) < m, v3{m} = []; end
M = [v1 v2' v3]';
X = M(:);

Shoaibur Rahman
Shoaibur Rahman 2014년 12월 20일
편집: Shoaibur Rahman 2014년 12월 20일
v1 = {'a' 'b' 'c'}';
v2 = {'d'}';
v3 = {'e' 'f'}';
Lv1 = length(v1); Lv2 = length(v2); Lv3 = length(v3);
n = max([Lv1 Lv2 Lv3]);
v1cell = [v1; cell(n-Lv1,1)];
v2cell = [v2; cell(n-Lv2,1)];
v3cell = [v3; cell(n-Lv3,1)];
v4 = [v1cell v2cell v3cell];

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by