2010-03-17 63 views
5

当我使用cell2mat时,我有许多空单元格显示为NaN的文件,但问题是当我需要获得平均值时,我无法使用它,因为它显示NaN错误。在Excel中,它忽略了NaN值,所以我如何在MATLAB中做同样的事情?如何摆脱MATLAB中的NaNs?

另外,我写使用xlswrite文件:

xlswrite('test.xls',M); 

我在所有行的数据,除了1我怎样写:

M(1,:) = ('time', 'count', 'length', 'width') 

换句话说,我想M(1,1)='time'M(1,2)='count'等等。我有从M(2,1)M(10,20)的数据。我怎样才能做到这一点?

+0

@Paul:矩阵“M”是单元阵列吗?我假设它必须包含字符串和数据值。在这种情况下,命令'xlswrite('test.xls',M);'似乎应该可以正常工作。它似乎出了什么问题? – gnovice 2010-03-18 02:57:18

+0

我不认为M是细胞,它是一个数字10,20的矩阵。我如何转换字符串,如果多数民众赞成我需要什么。 – Paul 2010-03-18 03:02:10

+0

我修改了ans来解决你的新问题。希望它可以帮助 – 2010-03-18 03:15:58

回答

7

使用 'ISFINITE' 功能摆脱所有NaN和无穷大

A = A(ISFINITE(A))

%创建包含列标题 的columnHeader = {”单元阵列列1','列2','列3','列4','列5',''};

%先写列标题 xlswrite('myFile1.xls',columnHeader); xlswrite('newFile.xls',M,'Sheet1','A2');

+0

感谢它的工作! – Paul 2010-03-17 19:50:53

+0

>检出: > http://www.mathworks.com/access/helpdesk/help/techdoc/ref/xlswrite.html – 2010-03-17 21:35:52

5

统计工具箱有几个统计函数来处理NaN值。请参阅nanmean,nanmedian,nanstd,nanmin,nanmax等。

+0

顺便说一下,min/max的工作方式与nanmin/nanmax相同。这是平均和中位数,你必须使用nanX功能。 – Jonas 2010-03-17 18:26:34

9

As AP correctly points out,可以使用函数isfinite在矩阵中查找并仅保留有限值。您也可以使用功能isnan。不过,从基质取出值可以有你的基质重塑成一个行或列向量的意想不到的后果:

>> mat = [1 2 3; 4 NaN 6; 7 8 9] % A sample 3-by-3 matrix 

mat = 

    1  2  3 
    4 NaN  6 
    7  8  9 

>> mat = mat(~isnan(mat)) % Removing the NaN gives you an 8-by-1 vector 

mat = 

    1 
    4 
    7 
    2 
    8 
    3 
    6 
    9 

另一种方法是使用一些功能从Statistics Toolbox(如果你有机会的话)是设计为deal with matrices containing NaN values。既然你提到考虑平均数,你可能想看看nanmean

>> mat = [1 2 3; 4 NaN 6; 7 8 9]; 
>> nanmean(mat) 

ans = 

    4  5  6  % The column means computed by ignoring NaN values 



编辑:要回答你的使用xlswrite额外的问题,此示例代码应该说明一个方式你可以写你的数据:

C = {'time','count','length','width'}; % A cell array of strings 
M = rand(10,20);      % A 10-by-20 array of random values 
xlswrite('test.xls',C);   % Writes C to cells A1 through D1 
xlswrite('test.xls',M,'A2:T11'); % Writes M to cells A2 through T11 
+0

+1指出重塑问题 – Jonas 2010-03-17 18:27:04

+0

谢谢,但是我没有尝试这个作为isfinite为我工作,因为我想要的只是得到平均值。 – Paul 2010-03-17 19:51:46

+0

@Paul:如果你平均的数据只是一维矢量,那么你就不必担心我上面提到的重塑问题了。 AP的简单解决方案就是您真正需要的。 ;) – gnovice 2010-03-17 20:45:12

0

你可以将NaN设置为a任意数字如下:

mat(isnan(mat))=7 // my lucky number of choice. 
0

可能为时已晚,但...

x = [1 2 3; 4 inf 6; 7 -inf NaN]; 
x(find(x == inf)) = 0; //for inf 
x(find(x == -inf)) = 0; //for -inf 
x(find(isnan(x))) = 0; //for NaN