필터 지우기
필터 지우기

Storing vectors of different length in one single vector

조회 수: 16 (최근 30일)
Mary
Mary 2012년 2월 9일
Hello, hope you can help me out here...
I have a for-loop which produces with every loop a vector of values. The vectors it produces can have different lengths (for example, the vector in the first round has 10 values, in the second round 15, in the third 2...). In the end I'd like to store the values of these vectors in one single vector, but i really don't know how to best do it.
Thanks a lot in advance!

채택된 답변

Jan
Jan 2012년 2월 9일
The slow way:
x = [];
for i = 1:100
y = rand(1, floor(rand*11));
x = [x, y]; % or x = cat(2, x, y)
end
Now the vector x grows in every iteration. Therefore memory for a new vector must be allocated and teh old values are copied.
Filling a vector, cleanup afterwards:
x = nan(100, 10);
for i = 1:100
n = floor(rand*11);
y = rand(1, n);
x(i, 1:n) = y;
end
x(isnan(x)) = []; % Now x is a column vector
Collect the vectors in a cell at first:
C = cell(1, 100);
for i = 1:100
C{i} = rand(1, floor(rand*11));
end
x = cat(2, C{:});
The overhead for creating the CELL is much smaller than the slow method of the growing array.
And if you the array is very large and the section is time-consuming, it matters that cat seems to have problem with a proper pre-allocation internally. Then FEX: Cell2Vec is more efficient.

추가 답변 (2개)

Shiva Arun Kumar
Shiva Arun Kumar 2012년 2월 9일

Walter Roberson
Walter Roberson 2012년 2월 9일
The problem isn't so much storing the variable-length information: the problem is in getting the information out afterwards.
You need to store one of:
  • the location of the start of each section
  • the length of each section
  • a unique marker between sections that cannot occur in the data itself
If you choose to store length information, you can store it separately, or you can prefix each segment with the segment length.
For example:
vector_of_data = [];
for k = 1 : whatever
newdata = as appropriate
vector_of_data = [vector_of_data length(newdata) newdata];
end

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by