How can I merge many rows of different lengths into a matrix?
    2 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
    Rupeng Li
 il 14 Dic 2018
  
    
    
    
    
    Risposto: Omer Yasin Birey
      
 il 14 Dic 2018
            Hi everyone! I encountered a problem in merging many rows of different lengths into a matrix, for example,
A=[1:2];
B=[3:7];
C=[1:10];
What I want to achieve is to have the following matrix:
D=[A;B;C]
% which does not work
% to be in the format of following
D=[1,2,0,0,0,0,0,0,0,0;
   3,4,5,6,7,0,0,0,0,0;
   1,2,3,4,5,6,7,8,9,10]
Does any one have a good way of filling zeros? The speed is also a concern as such operations would be repeated for millions of times .
Any help would be appreciated!
0 Commenti
Risposta accettata
  Stephen23
      
      
 il 14 Dic 2018
        >> C = {1:2,3:7,1:10};
>> L = cellfun('length',C);
>> M = zeros(numel(C),max(L));
>> for k = 1:numel(C), M(k,1:L(k)) = C{k}; end
>> M
M =
    1    2    0    0    0    0    0    0    0    0
    3    4    5    6    7    0    0    0    0    0
    1    2    3    4    5    6    7    8    9   10
0 Commenti
Più risposte (1)
  Omer Yasin Birey
      
 il 14 Dic 2018
        Hi Rupeng, as far as I understand you want to work with arrays. So you can use this code below
A=[1:2];
B=[3:7];
C=[1:10];
dimAdjustforA = max(max(length(A),length(B)),length(C))-length(A);%you have to set the dimension
A = [A zeros(dimAdjustforA,1)'];
dimAdjustforB = length(A)-length(B)%again to make it same dimension with the maximum one
B = [B zeros(dimAdjustforB,1)'];
D = [A;B;C]
0 Commenti
Vedere anche
Categorie
				Scopri di più su Matrix Indexing in Help Center e File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


