Appending data with different sizes

조회 수: 19 (최근 30일)
Maneesh
Maneesh 2018년 12월 21일
답변: Image Analyst 2018년 12월 21일
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
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

추가 답변 (2개)

M
M 2018년 12월 21일
편집: M 2018년 12월 21일
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
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.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by