# Appending data with different sizes

19 views (last 30 days)
Maneesh on 21 Dec 2018
Answered: Image Analyst on 21 Dec 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

madhan ravi on 21 Dec 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

M on 21 Dec 2018
Edited: M on 21 Dec 2018
The easiest way would be the following something like this:
a = [1 2 3];
b = [4 5 6 7];
n=size(b,2)
a_bis=[a zeros(1,n)];
c=[a_bis ; b];
You can edit this to your application by replacing the 1 to the size of a.

Image Analyst on 21 Dec 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.