简体   繁体   中英

Changing the size of a matrix in MATLAB

I am given the following matrices A of size 3x1 and B of size 5x1

A =   B=

1     A
2     B
3     C
      D 
      E

I want to convert matrix C in a 15x2 matrix

C =  

1   A  
1   B  
1   C  
1   D
1   E
2   A
  .
  .
  .
3   E

How can I make it?

Can be done with repmat

D = repmat(A',size(B,1),1);
C = [D(:),repmat(B,size(A,1),1)]

Here's a different alternative based on code for generating truth tables from Generate All Possible combinations of a Matrix in Matlab

ind = dec2base(0:power(5,2)-1,5)-47;
C = [A(ind(1:15,1) + 48, B(ind(1:15,2)];

And if you want to generalize it

m = max(size(A,1),size(B,1));
n = size(A,1)*size(B,1);
col = 2;
ind = dec2base(0:power(n,col)-1,n)-47;
ind = ind(1:n,:);
C = [A(ind(:,1) + 48, B(ind(:,2)];

The + 48 is just to convert your A matrix from a numerical matrix to a char matrix so that C can hold both number and letters. You can leave it out if A was already a char matrix.

What's useful about this technique is that by changing col , this generalizes to combing more than just 2 vectors in a similar fashion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM