MATLAB: Do I get a different length of the vector for different runs

dimensionsloopvectorworkspace

This is my code :
d=1
p=1
Number_Included = [ 3 7 2 ]
while p<=3
r(d:(d+Number_Included(p)-1)) = rand(1, Number_Included(p));
d=numel(r)+1
p=p+1;
end
the purpose is to generate 3 random numbers , then 7 random numbers, then 2 random numbers in the vector r , thus vector r is supposed to be of the dimension 1*12
1st run gives a vector r 1*12
2nd run, the dimensions of r change to 1*21!
I don't understand why thisis happening, could someone explain to me please, and how do I make sure that the dimensions stay 1*12( the desired) ???
I've notices that this problem does not happen when I clear the workspace

Best Answer

During the second run look carefully at the values that d will have.
On the while loop's first iteration everything works as you probably expect, because
d=1
but then on the while loop's second iteration this is the value of d:
d=numel(r)+1 % d = 13
and then on the third iteration this will be the value of d:
d=numel(r)+1 % d = 20
Of course this happens because you still have the entire 12-element vector in your workspace, leftover from the first run, and you are using that already-existing vector to determine the index d. In fact, this is quite easy to demonstrate, e.g.:
r = nan(1,12);
and then run your code:
r =
0.244767 0.016480 0.136528 NaN NaN NaN NaN NaN NaN NaN NaN NaN
r =
0.244767 0.016480 0.136528 NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.611294 0.591830 0.816990 0.740789 0.207290 0.699129 0.515550
r =
0.244767 0.016480 0.136528 NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.611294 0.591830 0.816990 0.740789 0.207290 0.699129 0.515550 0.706269 0.041856
"how do I make sure that the dimensions stay 1*12( the desired) ???"
Write simpler, more robust code:
  • avoid while, because for is much better when the number of iterations is known.
  • preallocate all output arrays before the loop (this would avoid the issue that you are seeing).
  • avoid complex indexing calculations.
  • avoid writing code that requires that you clear variables for it to work properly.
Something like this would be much more robust:
V = [3,7,2];
N = numel(V);
C = cell(1,N);
for k = 1:N
C{k} = rand(1,V(k));
end
Z = [C{:}]
Or even simply:
Z = rand(1,sum(V))