Extract data from a vector in a loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Plastic Soul
am 14 Mär. 2014
Kommentiert: Plastic Soul
am 15 Mär. 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 Kommentare
Akzeptierte Antwort
Joseph Cheng
am 14 Mär. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!