Combining two strings to a common string
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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)
추가 답변 (2개)
Andrei Bobrov
2013년 8월 29일
Variables = {'var1', 'var2', 'var3'};
Sectors = {'sec1', 'sec2'};
ii = fullfact([3 2]);
out = strcat(Variables(ii(:,1)),{'_'},Sectors(ii(:,2)));
댓글 수: 0
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 Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!