MATLAB Answers

0

Extract data from a vector in a loop

Asked by Plastic Soul on 14 Mar 2014
Latest activity Commented on by Plastic Soul on 15 Mar 2014
Hi everyone, First of all, I am a beginner.
I would like to make a function that would do the variance over specified number of samples "n". I need a variance of a signal (which is in a vector "x"). Basically, from a matrix "x", it takes first "n" number of samples, calculates variance and carries on to the next "n" samples. Now, I need those variance calculations in one vector, so I can plot it. That vector would have "length(x)/n" units. I made something like this:
function [a,b] = Variance( x, n )
a=zeros(1,length(x));
b=zeros(1,length(x));
for i=1:length(x)/n
a=x(i*n:(i+1)*n);
b=var(a);
end
end
This, of course does not work. I would appreciate if you could help out.

  0 Comments

Sign in to comment.

1 Answer

Answer by Joseph Cheng
on 14 Mar 2014
 Accepted Answer

So lets break it down. in your for loop
for i=1:length(x)/n
a=x(i*n:(i+1)*n);
b=var(a);
end
when i=1 you are getting x(1*n:2*n) and missing the the values of x from 1 to n. So you'll want to start with i-1 and go to the i value. example:
x=1:20;
for i=1:10
disp(x((i-1)*2+1:(i)*2))
end
Since you are assigning the calculations to a and b you should additionally be putting them into the correct array positions (i). so you'll have a(i) = __ ; and b(i) =var(a(i)); that way you get your length(x)/n arrays.
Another method of this is you can use reshape. example:
x=1:20
y = reshape(x,5,4);
b=var(y);
here you see that the reshape formed your buckets of n-samples for you.
~J

  2 Comments

Hi Joseph,
Thanks for a fast reply. I modified the array positions with a(i) and b(i), but now, I am getting error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
Here is the code:
function [a,b] = Variance( x, n )
a=zeros(1,length(x)/n);
b=zeros(1,length(x)/n);
for i=1:length(x)/n
a(i)=x(n*(i-1)+1:i*n);
b(i)=var(a(i));
end
end
Never mind, I think I did it with the other method:
function [ b,a ] = Var1( x,n )
a=reshape(x,n,length(x)/n);
b=var(a);
end
Seems like its working... Thanks a lot. If you notice anything wrong, let me know pls.

Sign in to comment.