Where's the bug in the following codes?
    9 ビュー (過去 30 日間)
  
       古いコメントを表示
    
fun=@(x,y)100*(y-x^2)^2+(1-x)^2;
x=-10:1:10;
y=-10:1:10;
[z,val]=fminsearch(fun,3,3);
0 件のコメント
採用された回答
  Star Strider
      
      
 2015 年 10 月 9 日
        You have to give fminsearch a function of one parameter vector. I created two versions of your ‘fun’ function, one to use as an argument to fminsearch and one for the plot, vectorising both functions so they will work:
% MAPPING:  b(1) = x,   b(2) = y
fun=@(b)100*(b(2)-b(1).^2).^2+(1-b(1)).^2;      % Argument To ‘fminsearch’
[z,val]=fminsearch(fun,[3,3])
x=-10:1:10;
y=-10:1:10;
[X,Y] = meshgrid(x,y);                          % Create Matrix Arguments
funplot=@(x,y)100*(y-x^2)^2+(1-x)^2;            % Plotting Version 
figure(1)
surfc(X, Y, funplot(X,Y))
grid on
I could have used the same function for both, but this is more straightforward.
5 件のコメント
  Star Strider
      
      
 2015 年 10 月 10 日
				
      編集済み: Star Strider
      
      
 2015 年 10 月 10 日
  
			@Shawn — Yes it should. I miscopied it somehow. (The code worked and produced the correct plot with the correct element-wise function operators.) It should look like ‘fun’:
funplot=@(x,y)100*(y-x.^2).^2+(1-x).^2;            % Plotting Version
EDIT — To plot the minimum as well as the function, the code becomes:
fun=@(b)100*(b(2)-b(1).^2).^2+(1-b(1)).^2;      % Argument To ‘fminsearch’
[z,val]=fminsearch(fun,[3,3])
x=-10:1:10;
y=-10:1:10;
[X,Y] = meshgrid(x,y);                          % Create Matrix Arguments
funplot=@(x,y)100*(y-x.^2).^2+(1-x).^2;         % Plotting Version
figure(1)
surfc(X, Y, funplot(X,Y))
hold on
plot3(z(1), z(2), funplot(z(1),z(2)), 'mp', 'MarkerSize',15, 'MarkerFaceColor','c')
hold off
grid on
view(-15, 30)
It plots the minimum with a slightly buried magenta pentagram with a red outline.
  Stephen23
      
      
 2015 年 10 月 10 日
				@Shawn Miller: one can vectorize funplot, and this can be called (and plotted) with vector/matrix inputs. funfmin stays the same.
その他の回答 (1 件)
  Stalin Samuel
      
 2015 年 10 月 9 日
        yrfun = @(x)100*(x(2)-x(1)^2)^2+(1-x(1))^2;
[z,val]=fminsearch(yrfun,[-10 10]);
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!