How I can save vectors in for loops

Dears, I want to know how can I save vectors in 3(or more) for loops My code is huge and I summarize it here.
for i=1:10
for j=1:15
for k=1:20
% some calculation
Vector1= something with size(1x2000) % size of Vector1 will be changed in each loop
end
end
end
finally I would like to attach all of Vector1 to one vector and capable to find the special array is related to which i and j and k.

 Accepted Answer

Since the length of the vector will change in each loop, I would use a cell array and a counter:
k1 = 0;
for i=1:10
for j=1:15
for k=1:20
% some calculation
k1 = k1 + 1;
Vector1{k1} = something with size(1x2000) % size of Vector1 will be changed in each loop
end
end
end

4 Comments

Sam sanati
Sam sanati on 3 May 2015
Edited: Sam sanati on 3 May 2015
Thanks Star Strider,
What about to recall the special array related to i,j,k. In other words after calculation of the all of Vector1. for example size (1x2000),(1x2500),(1x3200) ... , the Vector1total (which size is sum of all 2000+2500+3200+ ...) how can I find the special array. Imagine that for example array equal to 2 is nth array in the vector1total (1x2000+2500+3200...). how we can find that is related to which array of which vector1?
I do not understand your question, so I am not certain this will answer it.
You can keep whatever information you want in your cell array. For instance if you have:
x1 = (1x2000)
x2 = (1x2500)
x3 = (1x3200)
xc = [x1 x2 x3] % Concatenate Vectors
and you want to save the indices i,j,k as well, you can create ‘Vector1’ as:
Vector1{k1} = {i, j, k, xc};
or whatever you want in it.
Thanks for your quick reply and apologize for bad explanation. There is 2 question:
1- how to concatenate vectors in for loops? The number of vectors is too much (for example n is 2000).
xc=[x1 x2 ... xn]
I can not concatenate after end of last for.
2- after creation of xc, the n th array of xc (for example 12567 th) should be determine the related i,j and k.
Thanks again
My pleasure. Your explanation is not ‘bad’, sometimes it is not easy to describe what what we want our code to do.
If I understand you correctly:
1. The length of your vector (‘xc’ in my example) is determined by your computer’s memory. I do not know what you are calculating, so I cannot suggest a more efficient strategy.
2. In my example, i,j,k are stored as part of the cell element. If you want the cell array ‘Vector1’ to have 3 dimensions instead of 1, you can easily do that:
Vector1{i,j,k} = xc;
Then you can address each element individually. (You do not need the ‘k1’ counter if you do this.)

Sign in to comment.

More Answers (0)

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!