Extract data from a vector in a loop

2 次查看(过去 30 天)
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.

采纳的回答

Joseph Cheng
Joseph Cheng 2014-3-14
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 个评论
Plastic Soul
Plastic Soul 2014-3-14
编辑:Plastic Soul 2014-3-15
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
Plastic Soul
Plastic Soul 2014-3-15
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by