Appending data with different sizes
17 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
madhan ravi
2018-12-21
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 个评论
更多回答(2 个)
Image Analyst
2018-12-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!