Reshape row wise w/ different starting/ending elements number

后端 未结 3 1930
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 23:13

The problem is:

Product of known dimensions, 3, not divisible into total number of elements, 16.

this because i want to reshape a

相关标签:
3条回答
  • 2021-01-21 23:29

    You should add zeros in the beginnig. What I mean:

    vec      = [1:16]'
    nRow     = 3;
    nCol     = 6;
    zeroFill = nRow * nCol - length(vec);
    newVec   = [vec; zeros(zeroFill, 1)];
    mat      = reshape(newVec, [nRow nCol])
    
    0 讨论(0)
  • 2021-01-21 23:31

    Approach #1

    You can use vec2mat that's part of the Communications System Toolbox, assuming A as the input vector -

    ncols = 6; %// number of columns needed in the output
    out = vec2mat(A,ncols)
    

    Sample run -

    >> A'
    ans =
         4     9     8     9     6     1     8     9     7     7     7     4     6     2     7     1
    >> out
    out =
         4     9     8     9     6     1
         8     9     7     7     7     4
         6     2     7     1     0     0
    

    Approach #2

    If you don't have that toolbox, you can work with the basic functions to achieve the same -

    out = zeros([ncols ceil(numel(A)/ncols)]);
    out(1:numel(A)) = A;
    out = out.'
    
    0 讨论(0)
  • 2021-01-21 23:39

    You can also pre-allocate a vector of zeroes, fill in your data for as many elements as there are in your vector, then reshape it when you're done:

    vec = 1:16; %// Example data
    numRows = 6;
    numCols = 3;
    newVec = zeros(1:numRows*numCols);
    newVec(1:numel(vec)) = vec;
    newMat = reshape(newVec, numRows, numCols);
    
    0 讨论(0)
提交回复
热议问题