Parth Sane
Parth Sane

Reputation: 587

Create a matrix from a vector such that its height and width are powers of multiples in matlab

I have tried multiple solutions in matlab to convert a vector for example

A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]

into

B= [ 1  2  3  4 ]
     5  6  7  8
     9  10 11 12
     13 14 15 16 
     17  0  0  0
      0  0  0  0
      0  0  0  0
      0  0  0  0

Here the desired matrix is 8x4 or rather the height or width is any multiple of 4. This would mean the nearest greater multiple of 4 if we keep any one dimension(height or width) fixed for fitting all elements and padding the extra elements with zeroes. I have tried reshape like so

reshape([c(:) ; zeros(rem(nc - rem(numel(c),nc),nc),1)],nc,[])

Here c is the original vector or matrix, nc is the number of columns.

It simply changes the number of rows and cols but does not take into account the possible powers required by the condition for height and width. I don't have the Communications Toolbox which has the vec2mat function. Another possible alternative thought is to initialize a matrix with all zeroes and then assign. But at this point I'm stuck. So please help me matlab experts.

Upvotes: 0

Views: 102

Answers (1)

user2999345
user2999345

Reputation: 4195

i think this what you mean:

n = 4;
A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
B = zeros(n,ceil(numel(A)/n^2)*n);
B(1:numel(A)) = A;
B = B'

B = [ 1  2  3  4 
     5  6  7  8
     9  10 11 12
     13 14 15 16 
     17  0  0  0
      0  0  0  0
      0  0  0  0
      0  0  0  0]

Upvotes: 1

Related Questions