Вопрос

I have two cells:

Months1 = {'F','G','H','J','K','M','N','Q','U','V','X','Z'};
Months2 = 2009:2014;

How do I generate all combinations without running a loop so that I achieve the following:

Combined = {'F09','F10','F11','',...,'G09',.....};

Basically all combinations of Months1 and Months2 as in meshgrid.

Это было полезно?

Решение 3

You can convert cell array to indices with grp2idx, then use meshgrid, then strcat to combine strings. Before you also need to convert numeric Months2 vector to cell array of strings.

[id1,id2] = meshgrid(grp2idx(Months1),Months2);
Months2cell = cellstr(num2str(id2(:)-2000,'%02d'))';
Combined = strcat( Months1(id1(:)), Months2cell );

Другие советы

If you don't need cells and can use char arrays only, this can work:

Months1 = ['F','G','H','J','K','M','N','Q','U','V','X','Z']';
Months2 = num2str((2009:2014)');

[x, y] = meshgrid(1:12, 1:6);
Combined = strcat(Months1(x(:)), Months2(y(:),:));

and you can then reshape if required. I'm not yet sure how to do this with cells, though. Inspired by this post.

My take on the problem would apply ndgrid, datestr (to handle any millennium) and strcat to do the work:

yearStrings = datestr(datenum(num2str(Months2(:)),'yyyy'),'yy');
[ii,jj] = ndgrid(1:numel(Months2),1:numel(Months1));
Combined = strcat(Months1(jj(:)).',yearStrings(ii(:),:)).'

Note: Years change faster than the prefixed letters, so Months2 goes first in ndgrid, then Months1. IMO, this is more intuitive behavior than meshgrid, which forces you to think in x,y space to predict how the outputs vary.


Or instead of the strcat line:

tmp = [Months1(jj(:)).',yearStrings(ii(:),:)].';
Combined = cellstr(reshape([tmp{:}],[],numel(ii)).').'
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top