2016-10-16 18 views
1

質問逃した文字列の平均値(最も発生クラス)の列の値と番号の列を交換する方法Matlab。平均

を逃した値を置き換えますか?データの

例から取られました:'アイリスsetosa'

enter image description here

コードでNaNを置き換える、例えば

UCI ML Repo. Iris

私は

を持っています

これは値だけを置き換えますが、文字列も置き換えます。

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

以下の溶液は、問題を解決する:

  • (セルアレイは、異なる長さの文字列を保持するために必要とされる)セルアレイに最後のテーブル列を変換します。
  • Remove all NaN elements from cell array(NaN要素は次のセクションを混乱させます)。
  • Find most repeated string in cell array
  • stringColumn内のすべてのNaN要素を検索します(前のセクションに基づいてcellfunを使用しました)。
  • ほとんどの一般的な文字列で、indecesのRplace要素が見つかりました。

あなたはMatlabを初めて使うので、私のソリューションはあなたのために非常に複雑に見えます(それは私にとっては複雑です)。

は、次のコードサンプルを参照してください...私は見つけることcould't簡単な解決策、あるかもしれません:

%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で新しいですが、コーディングではありません) –