night owl
night owl

Reputation: 103

How to Sum through Vectors elements

I have a variable quantity that contains two vectors. I want to sum these quantity from i = 1 to n, where n = 100. When the program is ran, I can click on the variables in the work space to see the element values of the vectors for each column position. When executing the variable of its position I get the corresponding value, (for e.g., z(1) = 73.2360, z(2) = 63.3701, .... and so on). But what I cannot seem to figure out is how to index thee vectors for the sum to run through the elements of the two vectors. For example in a for loop. I also took a look at symsum(), but that needed just generic variables. I am trying to sum epsilon from i = 1 to 100, where z_i and w_i are vectors of interest. I hope the MWE will show more of what I want to accomplish.

MWE:

 a = 0.6;
 b = sqrt(16-a^2);
 c = 6.5;
 d = sqrt(225-c^2);
 xh = randn(1,100);
 yw = randn(1,100);
  z = a*xh + b*yw + 68;
  w = c*xh + d*yw + 160;

     n = 100;                              % # of data entries.
  zbar = ((1/n)*sum(z));                   % Height data.
  wbar = ((1/n)*sum(w));                   % Weight data.
 Zbarv = zbar*ones(1,100);                 % Height data vector.
 Wbarv = wbar*ones(1,100);                 % Weight data vector.

sz = sqrt((1/n)*((z-Zbarv)*(transpose(z)-transpose(Zbarv))));              
sw = sqrt((1/n)*((w-Wbarv)*(transpose(w)-transpose(Wbarv)))); 

czw = ((1/n)*(w-Wbarv)*(transpose(z)-transpose(Zbarv)));
rzw = czw/(sz*sw);

 b = wbar - ((czw/sz^2)*zbar);             % y-intercept
 m = czw/sz^2;                             % Slope
 epsilon = (1/(n-1))*sum((w-(m*z+b)).^2);  % Error

The epsilon should be summing this, but should be a sum from i=[1,100]. I do not know how to index the values of the w_i and z_i vectors to for the sum to run through them. I tried making a input variable to them like z(i) and w(i)but turned out messy.

Any suggestions?

Upvotes: 0

Views: 404

Answers (1)

Dan
Dan

Reputation: 45741

It sounds like you just want:

epsilon = (1/(n-1))*sum((w(1:100)-(m*z(1:100)+b)).^2);

Although since you w and z are just 100 elements long, I think this is the same as what you've done. So I think your code is actually correct as it stands.

For example if a = [1 2 3], then sum(a) is 6, you don't actually have to index a to get the sum. So your code is finding the sum of all 100 elements.

You should read up on the Matlab colon operator

The basic idea is that in matlab something like 1:10 is just short hand for [1 2 3 4 5 6 7 8 9 10] and you can use that to index a vector. So if we have a vector v = rand(100,1) then to get the first 10 elements of v it's just v(1:10)

Upvotes: 1

Related Questions