Filter löschen
Filter löschen

Storing vectors of different length in one single vector

18 Ansichten (letzte 30 Tage)
Mary
Mary am 9 Feb. 2012
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!

Akzeptierte Antwort

Jan
Jan am 9 Feb. 2012
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.

Weitere Antworten (2)

Shiva Arun Kumar
Shiva Arun Kumar am 9 Feb. 2012

Walter Roberson
Walter Roberson am 9 Feb. 2012
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

Kategorien

Mehr zu Performance and Memory finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by