【问题标题】:Convert numbers to sequence of numbers in cell-array rows将数字转换为元胞数组行中的数字序列
【发布时间】:2018-01-11 01:24:11
【问题描述】:

我想将[5,3,7] 转换为一个元胞数组,其中每一行的范围都是'1:to_the_respective_number'。然而,这似乎令人惊讶地难以实现。 谁能指出我哪里出错了?

nums=[5,3,7];
cellfun(@(x) 1:x, num2cell(nums),'UniformOutput',0)

ans =
  1×3 cell array
    {1×5 double}    {1×3 double}    {1×7 double}

我真正想要得到的是(在变量资源管理器中将它拼接在一起)

{1,2,3,4,5,[],[];1,2,3,[],[],[],[];1,2,3,4,5,6,7}
ans =
  3×7 cell array
    {[1]}    {[2]}    {[3]}    {[       4]}    {[       5]}    {0×0 double}    {0×0 double}
    {[1]}    {[2]}    {[3]}    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {[1]}    {[2]}    {[3]}    {[       4]}    {[       5]}    {[       6]}    {[       7]}

【问题讨论】:

    标签: matlab cell-array


    【解决方案1】:

    这里有两种方法可以得到想要的结果:

    1.使用arrayfun

    nums=[5,3,7];
    m = max(nums);
    row  = arrayfun(@(x){[num2cell(1:x) cell(1, m-x)]}, nums );
    result = vertcat(row{:});
    

    2.矢量化解决方案。

    nums=[5,3,7];
    m = max(nums);  
    result = repmat(num2cell(1:m),numel(nums),1);
    result(bsxfun(@gt, 1:m , nums.'))={[]};
    

    【讨论】:

      【解决方案2】:

      您想对数组进行操作,因此无需先转换为元胞数组。只需使用arrayfun(___, 'UniformOutput', false)。

      >> nums = [5,3,7];
      >> res = arrayfun(@(x) 1:x, nums, 'UniformOutput', false);
      

      结果是

      >> res{:}
      ans =
           1     2     3     4     5
      ans =
           1     2     3
      ans =
           1     2     3     4     5     6     7
      

      来自documentation...

      B = arrayfun(___,Name,Value) 将 func 与由一个或多个 Name,Value 对组参数指定的附加选项一起应用。 例如,要在元胞数组中返回输出值,请指定 'UniformOutput',false。当 func 返回无法连接到数组中的值时,您可以将 B 作为元胞数组返回。您可以将 Name,Value 对组参数与上述任一语法的输入参数一起使用。

      【讨论】:

        【解决方案3】:

        如果以零作为占位符的 3×7 数字矩阵就足够了,您可以将 1-D solution from here 调整为二维解决方案,如下所示:

        nums = [5 3 7];
        N = numel(nums);
        maxNum = max(nums);
        index = nums.*N+(1:3);
        
        res = [ones(N, 1) zeros(N, maxNum)];
        res(index) = -1;
        res = cumsum(res, 2);
        res(index) = -nums;
        res = cumsum(res(:, 1:maxNum), 2);
        

        以及生成的矩阵:

        res =
        
             1     2     3     4     5     0     0
             1     2     3     0     0     0     0
             1     2     3     4     5     6     7
        

        【讨论】:

          猜你喜欢
          • 2011-02-07
          • 2015-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多