Concatenate arrays of different length into a matrix
    120 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Stefano Grillini
 le 29 Août 2018
  
    
    
    
    
    Réponse apportée : Yang Liu
 le 26 Jan 2024
            Assume I have two arrays (time-series) of the form:
A = [NaN, 2, 3, 4, 5, 6, 7, NaN]
B = [5, NaN, 6, 7, NaN, 8, 9, 10, 11, 12]
Since two arrays of different length can not be horzcat (obviously), how can I combine them as to obtain a 8x2 matrix where available data match. I have long time-series, so this is just an example, but it points out how crucial it is to have matching observations. Ideally, the output should be:
 C = [NaN, 2, 3, 4, 5, 6, 7, NaN; 5, NaN, 6, 7, NaN, 8, 9, 10]
Thanks
Stefano
3 commentaires
  Stephen23
      
      
 le 29 Août 2018
				
      Modifié(e) : Stephen23
      
      
 le 29 Août 2018
  
			"Since two arrays of different length can not be horzcat (obviously),"
I didn't have any problems using horzcat:
>> A = [NaN, 2, 3, 4, 5, 6, 7, NaN];
>> B = [5, NaN, 6, 7, NaN, 8, 9, 10, 11, 12];
>> horzcat(A,B)
ans =
   NaN     2     3     4     5     6     7   NaN     5   NaN     6     7   NaN     8     9    10    11    12
Réponse acceptée
  Stephen23
      
      
 le 29 Août 2018
        
      Modifié(e) : Stephen23
      
      
 le 29 Août 2018
  
      Truncate to shortest length using indexing:
>> N = min(numel(A),numel(B));
>> [A(1:N);B(1:N)]
ans =
   NaN     2     3     4     5     6     7   NaN
     5   NaN     6     7   NaN     8     9    10
>> padcat(A,B)
ans =
   NaN     2     3     4     5     6     7   NaN   NaN   NaN
     5   NaN     6     7   NaN     8     9    10    11    12
5 commentaires
  Stephen23
      
      
 le 29 Août 2018
				
      Modifié(e) : Stephen23
      
      
 le 29 Août 2018
  
			@Stefano Grillini: you really have two choices: either interpolate to fill in the NaN data, or remove the entire row from your data wherever there is a NaN. Judging by your data interpolation does not make much sense, however removing the rows is easy:
idx = any(isnan(c),2);
new = c(~idx,:)
Plus de réponses (1)
  Yang Liu
 le 26 Jan 2024
        I'd say, the most straight forward method would be using cell to combine whatever dimension you have, and use Cell{a,b}(x,y) to access the elements.
0 commentaires
Voir également
Catégories
				En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



