Combining two strings to a common string
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Azzi Abdelmalek
am 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)
Weitere Antworten (2)
Andrei Bobrov
am 29 Aug. 2013
Variables = {'var1', 'var2', 'var3'};
Sectors = {'sec1', 'sec2'};
ii = fullfact([3 2]);
out = strcat(Variables(ii(:,1)),{'_'},Sectors(ii(:,2)));
0 Kommentare
Jos (10584)
am 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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!