Strange multiple vectors assignment
3 views (last 30 days)
Show older comments
Hi folks... I have a strange problem to solve...
Let's assume I have 5 vectors (V1,V2,V3,V4,V5), each of length 10.
Inside a 10 elements loop I'm generating the i-th (with 1=1:10) value of all 5 vectors...that is I'm generating the i-th vector of 5 values, that I have to assign to the series of vectors, at the i-th position.
The code follows:
for i = 1 : 10
something producing a vector P of 5 elements...
for j = 1 : 5
eval(['V',num2str(j),'(i)=P(j);']);
end
end
But this is very high time consuming! So I thought to make only one matrix with the 5 vectors and assign the values directly to each row of that matrix.
The code follows:
M = [V1,V2,V3,V4,V5]; % The vectors are columns
for i = 1 : 10
something producing a vector P of 5 elements...
M(i,:) = P;
end
Ok...it works and it is faster than the first option...
But...
My real dataset is huge!!!...
I have 3 hundreds of vectors of about 3 millions elements each one, and, even using MATLAB2010 64bit version, I cannot create the big 3 hundreds x 3 millions matrix...(I only have 4 Gb RAM)
So I have to come back to the two nested loops... And it is veeeeeery high time consuming....
Any idea?...
Any way to assign directly the i-th elements of a series of individual vectors?
Maybe exploting the fact that their name is Vxxx?....
I hope to have been clear enough
Thanks in advance
Simone
1 Comment
Daniel Shub
on 21 Sep 2011
I don't quite follow. With your nest loop with eval you are going to end up with 3 hundred vectors of 3 million elements. If you do not have enough RAM to create a 3e2x3e6 matrix, you probably are going to have difficulties creating 300 1x3e6 arrays.
Answers (2)
Jan
on 21 Sep 2011
If you store the huge vectors in a single matrix, you need a continuos free block of memory.
If you create the vectors dynamically by EVAL you need a certain level of boldness, because this is known to cause annoying errors. In addition the memory manager has no chance to get itself organized, if you poke new variables dynamically into the workspace. So I would avoid EVAL especially when working with huge array -- or better: in every case.
You can use a cell to store this different vectors. Then the memory must not be free as continuous block, which decreases the Out-Of-Memory errors. And this is a clean and safe method:
V = cell(5, 10);
for i = 1 : 10
... something producing a vector P of 5 elements...
for j = 1 : 5
V{j, i} = P(j);
end
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!