NaN when calculating average

6 次查看(过去 30 天)
I read data from a .xls file using xlsread. There are some 3000 rows with price data, all in number format in excel. I further try to calculate the average of previous 10 days for every day using mean2(prices(i-10,1):prices(i,1)). I do this for last 2990 rows. surprisingly a lot of these throw NaN. I have also run a check "isnan" on each element in prices and none of them tests positive. also stumbled on something:
isnumeric(NaN)
ans =
1
how is this working??

采纳的回答

David Young
David Young 2012-1-22
Although a NaN is not a number, it is of class double, and so it is numeric. If a NaN was not numeric, it could not be held in a matrix with other numbers.
Your problem is that prices(i-10,1):prices(i,1) may be empty, so mean2 returns NaN. In fact, that expression doesn't look likely to be correct. I suspect you intended to use mean2(prices(i-10:i, 1)).

更多回答(2 个)

Andrew Newell
Andrew Newell 2012-1-22
You could use nanmean to ignore the NaN's while calculating means:
prices = rand(20,20);
n = size(prices,1); m = size(prices,2); window=10;
runningMean = zeros(n-window,m);
for ii=1:n-window
runningMean(ii,:) = nanmean(runningMean(ii:ii+window-1,:));
end
Note that I am interpreting your statement of "previous 10 days" as the ten days before the current day. Your version is actually averaging 11 days.
  6 个评论
Atakan
Atakan 2012-1-22
This is my code:
function [randnormal]=atakan(a,b,m)
randnormal=[];
count=1;
while (count<=m)
R = normrnd(a,b);
u1=unifrnd(0,1);
u2=unifrnd(0,1);
y=tan(pi*(u1-1/2));
if (u2<=((sqrt(exp(1))/2)*(1+y^2)*(exp(1)^(-y^2/2))))
randnormal=[R;y];
end
count=count+1;
end
Pankaj
Pankaj 2012-1-23
Thanks Andrew - good solution - it helps!

请先登录,再进行评论。


Atakan
Atakan 2012-1-22
Hi; I want to ask a question to the main page. But it gives an error such that "we are sorry but something went wrong". What can I do?
  3 个评论
Atakan
Atakan 2012-1-22
I have tried many many times. But there is still a problem. If I send the question to you, can you ask the question for me? Because this is very important for me. thanks...
Jan
Jan 2012-1-22
Dear Atakan: The servers have severe problems currently.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by