Appending data with different sizes
    16 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
Hi,
I have a loop which produces data of differnt sizes and want to have the results in a single array.  The sizes of the data cannot be pre-determined.  For example 1st itteration produces the following
a = [1 2 3;4 5 6]
the second iteration produces 
a = [1 2 3 4;4 5 6 7;6 7 8 9]
I want the final result to be
b = [1 2 3 0 ;4 5 6 0;1 2 3 4;4 5 6 7;6 7 8 9]
Thanks
0 Commenti
Risposta accettata
  madhan ravi
      
      
 il 21 Dic 2018
        aa = [1 2 3;4 5 6];
b = [1 2 3 4;4 5 6 7;6 7 8 9];
n=size(b,2);
aa=zeros(size(a,1),size(b,2));
aa(:,1:size(a,2))=a(:,1:size(a,2));
Result=[aa;b]
Gives:
Result =
     1     2     3     0
     4     5     6     0
     1     2     3     4
     4     5     6     7
     6     7     8     9
0 Commenti
Più risposte (2)
  Image Analyst
      
      
 il 21 Dic 2018
        What if you kept the arrays in a cell array instead of a numerical array with zero padding?  You could do
numCells = 1000; % whatever....
ca = cell(numCells, 1); % Instantiate/preallocate.
for k = 1 : numCells
    ca{k} = GetArraySomehow();
end
Or you could just create a huge zero array, and then insert the current array into the right location, keeping track of the max columns, then just crop afterwards.
output = zeros(1000, 1000);
lastRow = 0;
lastCol = 0;
for k = 1 : whatever
    thisArray = GetArraySomehow();
    [theseRows, theseColumns] = size(thisArray);
    output(last+1:lastRow+theseRows, 1:theseColumns) = thisArray;
    lastRow = lastRow + theseRows;
    lastCol = max([theseColumns, lastCol]);
end
output = output(1:lastRow, 1:lastCol);
Whether this is faster than dynamically expanding it when needed, like the others suggested, is something you might want to test.  I'm just offering this preallocation as an example.  As a failsafe you might want to check in my code if lastRow or lastCol is more than the size you preallocated it for.  If so, you'd have to dynamically expand it, but this dynamic expansion would happen a lot less than the others because you're supposed to just guess at some size that in all likelihood would be plenty big enough to contain all the data.
0 Commenti
Vedere anche
Categorie
				Scopri di più su Logical 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!



