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.

采纳的回答

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)

更多回答(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