Appending data with different sizes
19 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Maneesh
le 21 Déc 2018
Réponse apportée : Image Analyst
le 21 Déc 2018
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 commentaires
Réponse acceptée
madhan ravi
le 21 Déc 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 commentaires
Plus de réponses (2)
Image Analyst
le 21 Déc 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 commentaires
Voir également
Catégories
En savoir plus sur Data Type Conversion 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!