Saturday, 15 September 2012

Passing additional arguments through function handle to do optimization in Matlab -



Passing additional arguments through function handle to do optimization in Matlab -

i have function optimize, f,in matlab, function depends on variable x=(x(1),x(2))over want optimize , 2 parameters n , c not need optimize, in other words, have matrix of values n , c , want find optimal x values each n , c. here code:

clear all; clc; close all; f=@(x,n,c)n*x(1)+(x(2)+3*c)/(x(1)+c); n=1:10 c=1:20 x=zeros(length(n),length(c)); fun{n,c}=@(x)f(x,n,c); options=optimset('algorithm','interior-point') x(n,c)=fmincon(fun{n,c},[0;0],[1 0;-1 0;0 1;0 -1],[40;0;40;0],[],[],[],[],[],options); end end ??? subscripted assignment dimension mismatch. error in ==> forloop2 @ 10 x(n,c)=fmincon(fun{n,c},[0;0],[1 0;-1 0;0 1;0 -1],[40;0;40;0],[],[],[],[],[],options); helps? give thanks much!

i'm afraid didn't inquire question, here's answer:

function myoptimization clear all; clc; close all; results=cell(10,20); n=1:10 c=1:20 options=optimset('algorithm','interior-point'); fmincon(@(x)fun(x,n,c),[0;0],[1 0;-1 0;0 1;0 -1],[40;0;40;0],[],[],[],[],[],options); resultingcoordinates=fmincon(@(x)fun(x,n,c),[0;0],[1 0;-1 0;0 1;0 -1],[40;0;40;0],[],[],[],[],[],options); results{n,c}=resultingcoordinates; end end results end function f=fun(x,n,c) f=n*x(1)+(x(2)+3*c)/(x(1)+c); end

you made @ to the lowest degree 3 errors in original code.

first, x(n,c) = fmincon... doesn't work because fmincon returns vector optimal coordinates first output argument. therefore, trying assign vector single location in matrix "x", source of error. set optimal coordinates in cell array, can store output coordinates. if wanted optimal "f-value" assigned results matrix, can utilize [~,f(n,c)]=fmincon... .

second, "x" bad name output matrix, if wanted save coordinates. may cause errors it's used represent input objective function, not optimum coordinates. utilize different name optimum coordinates or optimal function values, reflects these results.

third, don't need continuously re-allocate output matrix/cell array each time alter parameters. trying clear results each iteration, doesn't work if want save them.

i split objective function function, , optimization of function another.

i hope helps. in future, please seek define clear question on stack overflow.

matlab function optimization cell handle

No comments:

Post a Comment