题
我的文件中有许多空单元格,当我使用时这些空单元格显示为 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)
. 。我怎样才能做到这一点?
解决方案
使用“ISFINITE”功能,摆脱所有NaN和无穷大的
A = A(ISFINITE(A))
%创建包含列标题中的单元阵列 的columnHeader = { '1列', '第2列', '第3列', '第4列', '5列',”“};
%第一写列标题 xlswrite( 'myFile1.xls',的columnHeader);
%直接写数据中的列标题下方 xlswrite( 'newFile.xls',M '表Sheet 1', 'A2');
其他提示
正如美联社正确指出的那样, ,您可以使用该功能 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
统计工具箱有几个统计函数来处理NaN值。见nanmean,nanmedian,nanstd,nanmin,nanmax等
可以NaN的设定为像这样的任意数:
mat(isnan(mat))=7 // my lucky number of choice.
可能为时已晚,但...
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