2

The problem is:

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

this because i want to reshape a 16x1 matrix in a 3x6 matrix. The problem is that the start matrix has 16 elements and the final matrix has 18. Is there a smart way to reshape row wise and filling the missing element with 0s till the number of elements matches?

Of course I need a general method independent from those number since the size of matrices can change.

TBN: 0s should be at the end of the matrix

gmeroni
  • 571
  • 4
  • 16

3 Answers3

3

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.'
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • May I ask a question? Is this approach possibile if `ncols` is a vector? Let's say that i need to take the first 6 elements for the first row of `out`, then another 4 elements of `A`and then 2 0's to complete the row, ecc – gmeroni Jan 19 '15 at 14:14
  • 1
    @gmeroni I think that would be a lot different from what's proposed in the question posted, so it would suit better as a new question. Also, please consider using a sample matrix to demonstrate the expected output. Good luck! – Divakar Jan 19 '15 at 14:20
2

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);
rayryeng
  • 102,964
  • 22
  • 184
  • 193
1

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])
mehmet
  • 1,631
  • 16
  • 21