2016-10-16 207 views
1

問題Matlab。與平均

如何使用字符串的平均值(最多出現的類)和列數代替錯過的列值替換遺漏值?數據的

例子是選自:

UCI ML Repo. Iris

例如,'虹膜setosa'

enter image description here

代碼替換NaN我有

它僅替換值,但如何替換字符串。

function dataWithReplaced = replaceNaNWithAvg(data) 

dataWithReplaced = [ ]; 

averagePerCol = table2array(varfun(@nanmean, data(: , 1:4))); 

for i = 1:4 

    dataColumn = table2array(data(: , i)); 
    dataColumn(isnan(dataColumn)) = averagePerCol(1, i); 

    dataWithReplaced = [dataWithReplaced dataColumn]; 

end 

end 

我是MATlab的新手,對我來說很多事情都不是很明顯。

回答

2

以下方案解決了該問題:

由於您是Matlab新手,我的解決方案對您來說看起來會非常複雜(對我來說看起來很複雜)。
有可能是一個簡單的解決方案,我便無法找到...

請參見下面的代碼示例:

%Create data table for the example. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
VarName1 = [4.9; 7.3; 6.7; 7.2; 6.5; 6.4; 6.8; 5.7; 5.8; 6.4; 6.5]; 
VarName2 = [2.5; 2.9; 2.5; 3.6; 3.2; 2.7; 3.0; 2.5; 2.8; 3.2; 3.0]; 
VarName3 = [4.5; 6.3; 5.8; 6.1; 5.1; 5.3; 5.5; 5.0; 5.1; 5.3; 5.5]; 
VarName4 = [1.7; 1.8; 1.8; 2.5; 2.0; 1.9; 2.1; 2.0; 2.4; 2.3; 1.8]; 
VarName5 = {NaN; 'aa'; 'aa'; 'bbb'; NaN; 'ccc'; 'ccc'; 'ccc'; 'ccc'; 'dddd'; 'dddd'}; 
data = table(VarName1, VarName2, VarName3, VarName4, VarName5); 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

%Convert last table column to cell array. 
stringColumn = table2cell(data(:, 5)); 

%Remove all NaN elements from cell array 
%Reference: https://www.mathworks.com/matlabcentral/newsreader/view_thread/314852 
x = stringColumn(cell2mat(cellfun(@ischar,stringColumn,'UniformOutput',0))); 

%Find most repeated string in cell array: 
%Reference: https://www.mathworks.com/matlabcentral/answers/7973-how-to-find-out-which-item-is-mode-of-cell-array 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
y = unique(x); 
n = zeros(length(y), 1); 
for iy = 1:length(y) 
    n(iy) = length(find(strcmp(y{iy}, x))); 
end 
[~, itemp] = max(n); 
commonStr = y(itemp); 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

%Find all indeces of NaN elements in stringColumn. 
nanIdx = find(cell2mat(cellfun(@ischar,stringColumn,'UniformOutput',0)) == 0); 

%Rplace elements with NaN values with commonStr. 
stringColumn(nanIdx) = commonStr; 

%Replace last column of original table 
data(:, 5) = stringColumn; 
+0

謝謝。我知道了。我是MATlab的新手,但沒有編碼) –