David
David

Reputation: 77

Store vectors that result form for loop and then compute the average of all these vectors

I have a 4 by 4 matrix:

A=[rand(1) 2 -1 rand(1);  
   rand(1) 3 rand(1) 0;  
   rand(1) -5 -2 5;  
   9  0   0 rand(1)];

Now I would like to form a vector b to be the first column of the matrix A. So the vector b is

b=[rand(1)  
   rand(1)  
   rand(1)  
   9 ];

I would like to write a for loop that compute b many times say 100 then store these vectors in matrix C ( which now has size of 4*100) and then compute the mean of all columns of C. So far I wrote:

for j=1:100
   A=[rand(1) 2 -1 rand(1);...
      rand(1) 3 rand(1) 0;...
      rand(1) -5 -2 5;...
      9 0 0 rand(1)];
   b=A(:,1)
end

Every time the loop executed, it produces a vector, say b_1 then b_2,....,b_100. How to store them in matrix C=[b_1 b_2 ... b_100] and then compute the mean of matrix C over all columns so that the mean will be a vector of size 4 by 1 the same size as b.

Upvotes: 1

Views: 64

Answers (1)

Leos313
Leos313

Reputation: 5627

I don't have Matlab on this laptop but the little script should be like this:

for jj=1:100
C(:,jj)=[rand(1) ;...
  rand(1) ;...
  rand(1) ;...
  9 ];
end

The matrix C will contain all the column-vectors b. To access to any of them just use b(:,x) where x is the index-number or column that you want to use. For the average you can do something like this:

b_average=[mean(C(1,:)); mean(C(2,:)); mean(C(3,:));mean(C(4,:))];

Of course the last mean upon a vector with only 9 values hasn't meaning: I leave the code as it is just for completeness. Remember as well that the average of a vector with random numbers will be really close to the value zero if N is big enough (where N is the number of the sample in the vector of course).

Anyway, the for loop is not the best way to do this. Try to use something like this:

C=[rand(1,100);rand(1,100);rand(1,100);9*ones(1,100)];

or better (as it was point out by Adriaan)

C=[rand(3,100);9*ones(1,100)];

This line does the same of the for loop. Again: try to don't use the variable j and iin Matlab because they are reserved.

Upvotes: 1

Related Questions