Combining two strings to a common string

조회 수: 1 (최근 30일)
Karl
Karl 2013년 8월 29일
How can I combine the following two strings
Variables = {'var1', 'var2', 'var3'};
Sectors = {'sec1', 'sec2'};
to the common string
New = {'var1_sec1','var1_sec2', 'var2_sec1', 'var2_sec2', 'var3_sec1', 'var3_sec2' };
I guess there must be a loop involved here.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 29일
Variables = {'var1', 'var2', 'var3'};
Sectors = {'sec1', 'sec2'};
[ii,jj]=ndgrid(1:2,1:3);
cellfun(@(x,y) [x '_' y],Variables(jj(:)),Sectors(ii(:)),'un',0)
  댓글 수: 1
Karl
Karl 2013년 8월 29일
Thank you!
You guys have saved me a lot of time!

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

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2013년 8월 29일
Variables = {'var1', 'var2', 'var3'};
Sectors = {'sec1', 'sec2'};
ii = fullfact([3 2]);
out = strcat(Variables(ii(:,1)),{'_'},Sectors(ii(:,2)));

Jos (10584)
Jos (10584) 2013년 8월 29일
The easiest, and most user-friendly, way is, indeed to use for-loops. However, you can make advantage of the built-in function STRCAT and use only one loop
Variables = {'var1', 'var2', 'var3'}
Sectors = {'sec1', 'sec2'}
M = numel(Sectors)
Output = cell(M, numel(Variables)) % pre-allocation before a for-loop will speed it up
for k=1:M
Output(k,:) = strcat(Variables, '_', Sectors{k})
end
Output = reshape(Output,1,[]) % only necessary for cosmetic reasons

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by