2017-01-08 89 views
0

我已經從Matlab的Excel文件中讀取了一些數據。單元陣列已生成如下:如何在Matlab中將單元格數組轉換爲數值數組?

x={'11', 'NaN', 'NaN', '13', 24} 

欲單元陣列轉換爲數值矩陣(對於其他所需的計算),並在我的數字矩陣轉換「的NaN」元素爲零。我該怎麼做?

謝謝。

回答

2

您可以使用str2double將字符串轉換爲數值:

x={'11', 'NaN', 'NaN', '13', '24'}; 
nx = str2double(x); 

一旦你有數值,您可以用零替代nan S:

nx(isnan(nx))=0 
+0

@Yaser,如果輸入的是在問題這是行不通的 - 最後的值(24 )是一個數字,而不是一個字符串。看到[我的回答](https://stackoverflow.com/a/41530933/2627163)來處理這個問題。 – EBH

0

在你給的例子該問題存在混合內容(字符串和數字),因此需要2個步驟:

x = {'11', 'NaN', 'NaN', '13', 24}; % last value is a number 
isch = cellfun(@isstr,x); % find all strings 
numx(isch) = str2double(x(isch)); % convert the strings to numbers, and place the correcly 
numx(~isch) = cell2mat(x(~isch)); % extract the numbers and place the correcly 

然後你可以用零代替所有NaN S:

numx(isnan(numx)) = 0; 

結果:

numx = 

    11  0  0 13 24 
相關問題