5

我的文件有很多空单元格,当我使用时显示为 NaN cell2mat,但问题是当我需要获取平均值时,我无法使用它,因为它显示 NaN 错误。在 excel 中它忽略了 NaN 值,那么我该如何在 MATLAB 中做同样的事情呢?

另外,我正在使用以下方法编写文件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)。我怎样才能做到这一点?

4

5 回答 5

9

正如 AP 正确指出的那样,您可以使用该函数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

另一种选择是使用统计工具箱中的一些函数(如果您可以访问它),这些函数旨在处理包含 NaN 值的矩阵。由于您提到取平均值,您可能需要查看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
于 2010-03-17T18:21:10.910 回答
7

使用“isfinite”函数摆脱所有的 NaN 和无穷大

A=A(无限(A))

%创建包含列标题的单元格数组 columnHeader = {'Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5',' '};

%首先写入列标题 xlswrite('myFile1.xls', columnHeader );

% 在列标题下直接写入数据 xlswrite('newFile.xls',M,'Sheet1','A2');

于 2010-03-17T18:02:06.253 回答
5

Statistics Toolbox 有几个统计函数来处理 NaN 值。见 nanmean、nanmedian、nanstd、nanmin、nanmax 等。

于 2010-03-17T18:20:38.243 回答
0

您可以将 NaN 设置为任意数字,如下所示:

mat(isnan(mat))=7 // my lucky number of choice. 
于 2012-11-17T13:03:43.497 回答
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
于 2014-12-21T13:14:03.277 回答