Extract data from a vector in a loop
8 views (last 30 days)
Show older comments
Plastic Soul
on 14 Mar 2014
Commented: 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
Accepted Answer
Joseph Cheng
on 14 Mar 2014
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
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!