Combining two strings to a common string

1 view (last 30 days)
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.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 29 Aug 2013
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)

More Answers (2)

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

Jos (10584)
Jos (10584) on 29 Aug 2013
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

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!