1

Greetings: let's suppose I have a loop that will execute 20 times, and within that loop I'll obtain a vector of information whose length will increase, each iteration, from 2 to 20. Now suppose I have a matrix of dimension 20, and during each iteration, I'd like to store that vector to one row of the matrix. For n = 2, the vector is length 2, and when I assign it to the first row of the matrix, call it A, I might try something like A(1,:) = p. But, since the length of the first row is 2o, and length of p is 2, there's a mismatch. Any clever suggestions on how to get around this issue.

Thanks so much...

John Sevic

  • Could you ctl+c/v your code here? I might be able to vectorize it. – Shuhao Cao Apr 29 '13 at 17:47
  • Probably shouldn't be on math.SE, but A(row,1:numel(p)) = p should work. – Ross B. Apr 29 '13 at 17:55
  • Also manually pre-allocate p's length to be 20 would work too. – Shuhao Cao Apr 29 '13 at 17:56
  • If you don't necessarily need a matrix you can also try cell arrays. They allow vectors with different lengths. – Matt L. Apr 29 '13 at 18:18
  • @RossB.: "software that mathematicians use" is on-topic here. The stackoverflow FAQ says that questions about "software tools commonly used by programmers" are acceptable. I don't think that programmers use MATLAB. Did you have a different site in mind? – robjohn Apr 30 '13 at 08:49
  • I only meant from the point of visibility. I have seen many more MATLAB-related questions on SO, for example, than math.SE. – Ross B. Apr 30 '13 at 12:29
  • Thanks all, for your support. These suggestions worked. Of course, the easy way was to simply assign the vector 20x in the loop, to 20 distinct vectors, but a bridge with 20x the concrete will always work: it's economy of resources that are beautiful :) – John Sevic Apr 30 '13 at 14:11

1 Answers1

1

This can be accomplished as follows:

P = zeros(19,20); %Preallocate memory

for i = 2:20
    p = someFunction();
    P(1:i,i-1)=p;
end

This will store each vector p in a row of P.

Daryl
  • 5,598