2012-11-17 73 views
1

我正在使用fminsearch來通過擾亂某些參數來最小化粗等級協方差與精細等級協方差的平均值之間的誤差。這些是使用fminsearch其中我打電話目標函數的代碼行2行minimize_me使用三個參數我打算擾亂:使用fminsearch時出錯

opts = optimset('display', 'iter'); 
[x,fval,exitflag] = fminsearch(@(x) minimize_me(x(1), x(2), x(3)), [2, 5, 90], opts); 

功能minimize_me示出以下內容,它採用幾個多個功能的其體內:

function diff = minimize_me(a_minor, a_major, theta) 

%# Grid and model parameters 
nModel=50; 
nModel_want=1; 
nI_grid1=5; 
Nth=1; 
nRow.Scale1=5; 
nCol.Scale1=5; 
nRow.Scale2=5^2; 
nCol.Scale2=5^2; 
nCell.Scale1=nRow.Scale1*nCol.Scale1; 

%% Covariance computation, averaging and difference of coarse and fine scale averaged covariances 

% Reading files by using the function 'general_gslib_file_to_mat.mat' 
[Deff_matrix_NthModel,~,~]=general_gslib_file_to_mat(nModel,nCell.Scale1,nModel_want,nI_grid1,Nth,'effective_dispersivity_coarsegrid5x5_gslib_format'); 

%# Maximum value of covariance/variogram at coarse scale 
sill = var(reshape(Deff_matrix_NthModel,nCell.Scale1,1)); % variance of the coarse data matrix of size (nRow.Scale1 X nCol.Scale1) 

%% Compute the covariance at different lags using the function general_CovModel.m 

for ihRow = 1:nRow.Scale1 
    for ihCol = 1:nCol.Scale1 
     [cov.Scale1(ihRow,ihCol),heff.Scale1(ihRow,ihCol)] = general_CovModel(theta, ihCol, ihRow, a_minor, a_major, sill, 'Exp'); 
    end 
end 

for ihRow = 1:nRow.Scale2 
    for ihCol = 1:nCol.Scale2 
     [cov.Scale2(ihRow,ihCol),heff.Scale2(ihRow,ihCol)] = general_CovModel(theta, ihCol/(nCol.Scale2/nCol.Scale1), ihRow/(nRow.Scale2/nRow.Scale1), a_minor, a_major,... 
      sill/(nRow.Scale2*nCol.Scale2), 'Exp'); 
    end 
end 

%# Scale-up of fine scale values by averaging which is done using the function general_AverageProperty.m 
[covAvg.Scale2,var_covAvg.Scale2,varNorm_covAvg.Scale2] = general_AverageProperty(nRow.Scale2/nRow.Scale1,nCol.Scale2/nCol.Scale1,1,nRow.Scale1,nCol.Scale1,1,cov.Scale2,1); 

%# Difference between the coarse scaled covariance and average of fine scale covariance 
diff = (covAvg.Scale2 - cov.Scale1)^2; 
end 

但是,在運行的前所示代碼的前兩行,我得到這個錯誤:

??? Subscripted assignment dimension mismatch. 

Error in ==> fminsearch at 195 
fv(:,1) = funfcn(x,varargin{:}); 

有人可以指出什麼是錯的?謝謝!

回答

3

問題是,你沒有提供足夠的人來測試你的代碼。

所以你應該......

  • 瞭解如何使用調試器!在任何情況下都是一個好主意。這將幫助你發現你做錯了什麼,但也教你使用一個有價值的工具。

  • 用起始值測試一次函數。它返回什麼?你試過這個嗎?總是做這個測試。驗證你的目標是否符合你期望的目標。

Fminsearch需要一個標量輸出來最小化。你的功能是否給予了這個?

哦,順便說一下,定義一個名爲diff的變量或任何在MATLAB中已經存在的有用工具是一個糟糕的主意。否則,你只是懇求在代碼中創建難以發現的錯誤。

+0

我錯過了'fminsearch'的標準,它說'fminsearch' **找到標量函數**的最小值。這有助於運行代碼。謝謝! – Pupil

+0

@S_H - 非標量函數很難「最小化」。這些通常被稱爲多標準優化,但我不是積極的,這是你正在嘗試做的。如果你有多個你想要最小化的輸出,那麼你需要把它變成一個標量函數。通常使用術語的平方和,或者可以採用術語的線性組合,使總和最小化。 – 2012-11-18 22:05:02

+0

@ woodchips:確實,我把我想要最小化的矩陣作爲「規範」。但是,我沒有得到滿意程度的優化解決方案。具有諷刺意味的是,我用L-2範數得到的「min f(x)= 0.282556」給出的數據更接近於我用L-1範數得到的「min f(x)= 0.257489」的數據。 – Pupil