MatLab fmin function - function

I have an .m file in matlab named PowerMinimiser and two functions in it
function PowerMinimiser
PowerOut = fmin(minFunction,0,100);
display(PowerOut)
end
and
function PowerOut = minFunction(varargin)
RunMode = 2;
ThresholdValue = 10;
if nargin > 0
ThresholdValue = varargin{1};
end
%Receive PowerOut value from .main file and pass in ThresholdValue and
%RunMode values:
[PowerOut] = main(ThresholdValue,RunMode);
end
Now what I would like to do is use the matlab fmin function so that I can find a value for the variable ThresholdValue which will give the lowest value possible for the variable PowerOut. The value for ThresholdValue is a number between 1 and 100, and is passed into a function in the main.m where a number of calculations are done and then a value for PowerOut is outputted.
Using the minFunction function I am able to receive and pass the variable fine, using the line
[PowerOut] = main(ThresholdValue,RunMode);
but I am not sure how to use the fmin function to get the value of ThresholdValue that gives the lowest value for PowerOut. I would like the ThresholdValue value to be shown once the fmin has done the necessary calculations. How can I do this? Any help would be greatly appreciated.
Thanks

You should use function fminbnd, which replaced fmin function in newer versions of Matlab. To pass function as an argument to fminbnd use # in front of the function name, like this:
PowerOut = fmin( #minFunction, 0, 100 );

Related

Assign function argument to global variable of the same name

Is it possible to set a global variable from within a function that takes that same variable name as an argument?
var a:int = 0;
function test(a:int)
{
a *global* = a *local*;
}
test(1);
trace(a) // traces 0 but I'd like it to trace 1
(The reason why I'd like to do this, is to avoid constantly coming up different variables names for the same things)
Thanks in advance.
You could refer to it explicitly as this.a = a; in your function test
In this case this is the class instance that holds this variable. In case of a static variable, you can use ClassName.a = a.

Matlab fminsearch options/restrictions

I have this function in Matlab which is supposed to find the smallest value possible for minValuePossible, by varying the two initial set values of inValues. How can I set the fmin search function to NOT try negative values while trying to find the minimum? Also how can I set the number of different variations the fminsearch function performs while trying to find the minimum? Because currently it tries somewhere around 20 different combinations of the two inValues and then completes. Maybe define the amount by which it changes each value? How would I do that?
function Valueminimiser
inValues = [50,50];
minValuePossible = fminsearch(#minimiser, inValues);
function result = minimiser(inValues)
x=inValues(1);
y=inValues(2);
RunMode = 2;
ValueOne = x;
ValueTwo = y;
[maxSCRAout] = main(RunMode,ValueOne,ValueTwo);
result = minValuePossible;
end
end
How can I set the fmin search function to NOT try negative values while trying to find the minimum?
Add the constrains of the values of your minimiser function at its beginning. If you meet this constrains then return a huge function value of minimizer. This will prevent fminsearch consider numbers which are not in your interest:
function result = minimiser(inValues)
if (sum(inValues < 0) > 1) % check if there is any negative number in input variable
result = hugeValue; % give a big value to the result
return; % return to fminsearch - do not execute the rest of the code
end
x=inValues(1);
y=inValues(2);
RunMode = 2;
ValueOne = x;
ValueTwo = y;
[maxSCRAout] = main(RunMode,ValueOne,ValueTwo);
result = minValuePossible;
Also how can I set the number of different variations the fminsearch function performs while trying to find the minimum?
You can define options of fminsearch by using optimset function. The parameter of optimset 'MaxFunEvals' is the maximum number of evaluations -- notice that this cout even the values you constrained, so maybe setting 'TolX' as advised by #slayton might be better if you are concerned about the accuarcy.
options = optimset('MaxFunEvals',numberOfVariations);
minValuePossible = fminsearch(#minimiser, inValues,options);
The docs for fminsearch don't describe a way to restrict the domain of the function you want to minimize.
If you want to restrict the range to all non-negative numbers then you can simply wrap your function in a call to abs, depending on the syntax .
minValuePossible = fminsearch( #(x)(minimiser( abs(x) ) ), inValues);
If you are worried about it constantly converging to the same minima then try a variety of different initial values.
Lastly you can alter the termination tolerances for X and minValuePossible using the TolX and TolFun input parameters. This is done with standard param value syntax: function(...., 'Param', value)
fminsearch( #(x)(minimiser(abs(x))), inValues, 'TolX', x_tolerance);

Cannot pass function handle as an argument of a function

I'm new to Matlab and I'm trying to write custom function in matlab that would take function handle as one of its arguments.
I'm getting this error all the time:
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Trying to debug I performed following test: I run command x = fminbnd(#humps, 0.3, 1). I proceeded as expected - I got result x = 0.6370.
So I created custom function called train and I copied ALL the code of function fminbnd to the file train.m. The only thing that I changed is the name, so that code of functions fminbnd and train is now identical except for the names.
Now I run both functions with the same argument and the custom function throws error while original fminbnd returns correct answer.
Here is the code:
>> x = fminbnd(#humps, 0.3, 1)
x =
0.6370
>> x = train(#humps, 0.3, 1)
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Here is header of function train (everything else is copied from fminbnd):
function [xf,fval,exitflag,output] = train(funfcn,ax,bx,options,varargin)
Where is the problem?
Doing a which train showed me that there is a function in the neural network toolbox of the same name.
/Applications/MATLAB_R2009b.app/toolbox/nnet/nnet/#network/train.m % network method
You may be running the nnet train.m rather than the one you think you're running. Are you in the directory containing your train.m? When I made sure I was in the right directory, I got it to work:
>> which train
/Users/myuserid/train.m
>> x = train(#humps,0.3,1)
x =
0.6370
Maybe you can name your file something else like myfminbnd.m instead?
Instead of duplicating the whole fminbnd function, try:
function varargout = myfminbnd(varargin)
varargout = cell(1,nargout(#fminbnd));
[varargout{:}] = fminbnd(varargin{:});
end
this will work as an "alias" to the existing function:
>> fminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
>> myfminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
(you can get the other output arguments as well)

Matlab call a function from a function

I have two functions:
function [] = func_one()
S.pb = uicontrol('style','push','unit','pix','posit',[20 20 260 30],
'string','Print Choices','callback',{#func_two,S});
and I have the second function:
function [a] = func_two(varargin)
a = 'alon';
end
I want func_one to return the variable a of func_two. How can I do that please?
I tried:
function [a] = func_one()
But I guess I have to do something with 'callback',{#func_two,S})
Thank you all!
If, as you say, you want func_one to return the value a in func_two then the easiest way to do this without using a callback is:
function [a] = func_one()
S.pb = uicontrol('style','push','unit','pix','posit',[20 20 260 30],
'string','Print Choices');
a = func_two()
The above will allow you to say run a=func_one and a will be the string 'alon'.
If you really really want func_two() to be a callback of your pushbutton, and you want a='alon' to be assigned in the workspace of func_one (the function that calls func_two) then put this in func_two
assignin('caller','a',a)
And if neither is what you want, then maybe you can indicate why you want func_one to return what func_two returns - like the exact interaction you are hoping to have with your GUI and how it differs from what you're actually experiencing.
If you are designing a GUI programmatically, I suggest you use nested functions to share data. Example:
function IncrementExample()
x = 0;
uicontrol('Style','pushbutton', 'String','(0)', ...
'Callback',#callback);
function callback(o,e)
%# you can access the variable x in here
x = x + 1;
%# update button text
set(o, 'String',sprintf('(%d)',x))
drawnow
end
end

Calling function with changing input parameters in a loop Matlab

I have caught myself in a issue, I know its not that difficult but I couldnt figure out how to implement it. I have an m file that looks like
clear;
PVinv.m_SwF=20e3
for m=1:1:70;
PVinv.m_SwF=PVinv.m_SwF+1e3;
Lmin = PVinv.InductanceDimens();
Wa_Ac = PVinv.CoreSizeModel();
PVinv.CoreSelect(Wa_Ac);
[loss_ind_core,loss_ind_copper] = PVinv.InductorLossModel(PVinv.m_L_Selected);
Total_Inductor_Loss=loss_ind_core+loss_ind_copper
plot(PVinv.m_SwF,Total_Inductor_Loss,'--gs');
hold on
xlim([10e3 90e3])
set(gca,'XTickLabel',{'10';'20';'30';'40';'50';'60';'70';'80';'90'})
grid on
xlabel('Switching Frequency [kHz]');
ylabel('Power loss [W]');
end
And the function that is of interest is CoreSelect(Wa_Ac)
function obj = CoreSelect(obj, WaAc)
obj.m_Core_Available= obj.m_Core_List(i);
obj.m_L_Selected.m_Core = obj.m_Core_Available;
end
I want to change the value of i from obj.m_Core_List(1) to obj.m_Core_List(27) within that for loop of main m file. How can I get the value of the function coreselect when I call it in main m file
For eg for m=1 to 70 I want the function to take the value of i=1 then execute till plot command and then same with but i=2 and so on
Any suggestion would be really helpful
I'm not sure I understand your question perfectly, but I think you want to pass an index i to the CoreSelect function, and loop i from 1 to 27 outside of the function. Try this:
function obj = CoreSelect(obj, WaAc, i)
...
end
for i=1:27,
PVInv.CoreSelect(WaAc,i);
end