Concatenate unequal sized arrays produced in a loop

I have a for loop (d = 1:57) for which I am trying to save the results in a single matrix, however each iteration produces a different length of array (e.g 1x58 single, 1x46 single, 1x59 single, ...). It is not possible to know the length of the longest array produced since I'll be running the same loop with various inputs and keeping track of the lengths will be tedious. How can I concatenate the arrays produced from the loop into one matrix perhaps by adding NaNs to the shorter arrays. Some suggested storing the vectors in matrix as result(d,:) which of course gives an error.
Result should have the dimension (57xlength of longest array).

 채택된 답변

Star Strider
Star Strider 2015년 11월 9일
I would use a Cell Array.
for d = 1:57
A{d} = ...
end
Notice the use of curly brackets ‘{}’ to denote the cell array elements.

댓글 수: 10

SMA
SMA 2015년 11월 9일
That does not work since my result matrix is an array; "Cell contents assignment to a non-cell array object."
I can't use mat2cell because I don't know what will be the dimensions after each iteration.
There must be something else about your data that you did not describe. This code runs without error (forcing single-precision):
for d = 1:5
A{d} = single(randi(99, 1, d*10));
end
SMA
SMA 2015년 11월 9일
Thank you, I'd have to check why the problem is arising.
My pleasure.
SMA
SMA 2015년 11월 10일
Some error in the code was creating the issue. So now that I have a cell array (with 57 cell arrays in it), is there any way I can convert it to a table or matrix by adding NaN to the shorter-length arrays.
Yes. It resisted my efforts at elegant solutions such as cellfun so loops will have to do. The initial loop changed to store the lengths of the individual vectors as they’re created. The second loop creates the matrix:
for d = 1:5
A{d} = single(randi(99, 1, d*10));
Asz(d,:) = size(A{d}); % Size Of Each Vector
end
Colmax = max(Asz(:,2)); % Maximum # Columns
Amtx = NaN(d,Colmax); % Preallocate
for k1 = 1:d
Amtx(k1,1:Asz(k1,2)) = A{k1}; % Fill Matrix
end
I checked it with my test data and it produces the correct matrix.
SMA
SMA 2015년 11월 10일
Works perfectly! Thank You!
My pleasure!
I found this helpful.. thank you
My pleasure.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

SMA
2015년 11월 9일

댓글:

2019년 6월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by