3
votes

I am running a for loop in MATLAB. Each iteration produces a vector of length different than the vector created in the previous iteration. Is there any why to recover each individual vector? In the end I want to concatenate each of these vectors. My code is something like

for i=1:n 
    v = zeros(1,i)
end

so after i=n, v will be a one by n vector, but I also want to recover the vectors for any i. In my code, each vector, v, is not a zero row vector, but a vector of varying size. Thanks.

2

2 Answers

6
votes

I'd already typed this when Rody's post (+1) came through so figured I might as well post it too. An alternate solution that is very slightly less efficient (I did some timed runs, the differences were marginal) than Rody's but avoids the complicated indexing is:

A = cell(1, n);
for i = 1:n
    A{1, i} = zeros(1, i);
end
Soln = cat(2, A{:});

I store the varying length row vectors in a cell array through the loop then concatenate them in the final step.

3
votes

The simplest way is like so:

w = [];
for i=1:n 
    v = zeros(1,i);

    %# your stuff here      

    w = [w v];
end

Which produces the vector w, which is the concatenation of all generated vectors v.

Note however that this is slow, since w grows each iteration. A slightly more complicated but more efficient solution would be this:

w = zeros(1, sum(1:n) );
j = 1;
for i=1:n 
    v = zeros(1,i);  

    %# your stuff here      

    w(1, j:j+i-1) = v;
    j = j+i;
end