2010-03-17 31 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