필터 지우기
필터 지우기

Extract data from a vector in a loop

조회 수: 2 (최근 30일)
Plastic Soul
Plastic Soul 2014년 3월 14일
댓글: Plastic Soul 2014년 3월 15일
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