[英]How do I get rid of NaNs in MATLAB?
當我使用cell2mat
時,我有許多空單元格的文件顯示為NaN,但問題是當我需要獲得平均值時,我無法使用它,因為它顯示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)
。 我怎樣才能做到這一點?
正如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
使用'isfinite'函數來消除所有NaN和無窮大
A = A(ISFINITE(A))
%創建包含列標題的單元格數組columnHeader = {'Column 1','Column 2','Column 3','Column 4','Column 5','}};
%首先寫下列標題xlswrite('myFile1.xls',columnHeader);
%直接在列標題xlswrite('newFile.xls',M,'Sheet1','A2')下面寫入數據;
Statistics Toolbox有幾個統計函數來處理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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.