【问题标题】:meshgrid equivalent for strings等效于字符串的网格网格
【发布时间】:2014-04-02 18:16:09
【问题描述】:

我有两个单元格:

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

如何在不运行循环的情况下生成所有组合,以便实现以下目标:

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

基本上Months1Months2 的所有组合,如meshgrid

【问题讨论】:

    标签: string matlab concatenation string-concatenation cell-array


    【解决方案1】:

    如果您不需要单元格并且只能使用 char 数组,这可以工作:

    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(:),:));
    

    然后您可以在需要时reshape。不过,我还不确定如何用细胞做到这一点。 灵感来自this 帖子。

    【讨论】:

    • 我好像迟到了 34 秒 :)
    • 你是对的,不需要转换为单元格。虽然 OP 想要 F09,而不是 F2009,所以需要一些处理。
    【解决方案2】:

    我对这个问题的看法将适用于ndgriddatestr(处理任何千年)和strcat 来完成这项工作:

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

    注意:年份的变化比前缀字母快,所以 Months2 先出现在 ndgrid 中,然后是 Months1。 IMO,this is more intuitive behavior than meshgrid,它迫使您在 x,y 空间中思考以预测输出如何变化。


    或者代替strcat 行:

    tmp = [Months1(jj(:)).',yearStrings(ii(:),:)].';
    Combined = cellstr(reshape([tmp{:}],[],numel(ii)).').'
    

    【讨论】:

      【解决方案3】:

      您可以使用grp2idx 将元胞数组转换为索引,然后使用meshgrid,然后使用strcat 组合字符串。在您还需要将数字 Months2 向量转换为字符串元胞数组之前。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-14
        • 2016-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多