How to locate the answer in the given code?
Show older comments
I have a function named as fobj1Mathworks.m. I call this function with an algorithm called NBA1. The purpose of calling the given function in the algorithm is to estimate the desired vector u (defined inside the function fobj1Mathworks) with the help of the algorithm. When I click the run button in MATLAB, it gets executed and gives me the answer in the variable ans in the command window.
What I want? I want to locate the line in the algorithm which gives this answer and stores it in the variable ans. Furhter, I want to find the corresponding fitness value where it is sotred inside the algorithm? I want to display that also in the command window alongwith the ans.
6 Comments
Dyuman Joshi
on 24 Dec 2023
Edited: Dyuman Joshi
on 24 Dec 2023
The outputs from the file NBA1 are bestX and fMin, and not ans. And you should not use ans as variable.
It's not clear which line you are referring to. It will be better if you could specify more about the line or just explicitly state it.
Sadiq
on 24 Dec 2023
Dyuman Joshi
on 24 Dec 2023
"But if you run the NBA1, you will see that these outputs are not displayed in the command window. But instead output is displayed in the command window as ans."
If you call a function which provides multiple outputs without specifying those outputs, only the 1st output will be displayed.
You should called the function NBA1 like this -
[out1, out2] = NBA1(inputs)
"Further, I don't understand that the input arguments to the algorithm are defined inside the algorithm and not outside and still it runs. Usually when I run a function like this, it gives me an error as "Not enough input arguments". But here NBA1 doesn't give such error."
If you have defined a function that requires input, you will need to provide the inputs when you call it. If you don't, you will get the error you mentioned.
However, it does not matter if you use those values or don't.
Sadiq
on 24 Dec 2023
Dyuman Joshi
on 24 Dec 2023
Edited: Dyuman Joshi
on 24 Dec 2023
"But still when I run it"
How are you running it? Please specify.
"It doesn't provide me the desired vector like u."
If u is a desired output, why have you not defined it as an output?
Dyuman Joshi
on 24 Dec 2023
Edited: Dyuman Joshi
on 24 Dec 2023
@Sadiq, see the first if condition statement (line 8 to line 33) - It checks if the number of inputs provided are less than 1 (i.e. no inputs are provided) or not. If they are less than 1, the statement defines the values to be used.
That is not a good check, but we'll dive into that later.
So, when you press the green button, MATLAB calls the function without any input, thus the if condition is triggered and the code runs accordingly.
And as you have not specified any output variables, the output is given as ans.
You should not run a function using the Green colored Run button. You should call it - using the function name, providing inputs and specifying outputs.
Answers (2)
John D'Errico
on 24 Dec 2023
Edited: John D'Errico
on 24 Dec 2023
Let me expand on what @Dyuman Joshi has said. Suppose you use any function in MATLAB. We will see what happens here, if it is used without a return argument.
clear
whos
I've done an initial whos, just to show that nothing is in the workspace, before anything else happens. Now I'll compute the mean of the integers 1:5. We expect 3.
mean(1:5)
whos
Do you see that now, a variable named ans was created? ans now contains the result of the mean function. This happens whenver you use any function that returns a result, but where the result was not stored in a named variable. And because I used no semi-colon on the line, ans was also reported in the command window.
Instead, you want to save the results of your function in a variable, named of your own choosing. I'll do another clear first so we are starting fresh.
clear
xmean = mean(1:5)
whos
Do you see that ans was not created in the second call? Instead, I stuffed the result into a variable of my own choice.
So, what happens when you call any function (your own function or not) which returns an output variable, but you do not assign it into a variable? You can see MATLAB thinking internally (sorry if I anthropomorphize this) that hey, I need to store this result somewhere, but they never gave me a name. I'll just call it ans.
Anyway, whenever you see the variable named ans appear in your workspace, that is because you made the mistake of not providing a place to return a result from some function. This can be a problem if you ever try to use ans as a variable name, becuase it will get overwritten by accident. So NEVER use ans as a variable name. We can see this happen in one final test.
clear
ans = 12;
whos
So now I have intentionally created a variable named ans. But then I'll use mean, again with no output assigned.
mean(1:5)
whos
And now we see the danger of using ans as a variable name. It can get accidently overwritten. ans now contains the number 3, even though we assigned it the value 12 previously. DON'T USE ans. That just begs for trouble in the future for you.
Finally, you ask how to find where ans was created inside your code. That may have been in many places, that is, anywhere you used a function, but gave it no place to store the result. You are also asking some side questions about insufficient inout arguments. These are an entirely different problem, but they also tell me you don't understand functions in general. Having already written a book here, I will leave that to someone else to answer your many side problems about functions.
10 Comments
Sadiq
on 24 Dec 2023
Sadiq
on 24 Dec 2023
But when I try to run the original arguments with so many input arguments, it doesn't give me that error. Why it is so?
In the original code, M, pop and dim had fixed numerical values given to them withing the code. Now - if you don't assign values to dim, pop and dim and just call the function as
[ bestX, fMin, time ] = NBA22( FitFunc, iter, pop, dim,lb,ub)
- what values should the code use for them ? You supplied "not enough input arguments" for the code to work.
John D'Errico
on 24 Dec 2023
Edited: John D'Errico
on 24 Dec 2023
"Now when I try to run it by clicking the run button"
You don't use the RUN button for a function!!!!!!!!
Run applies only to scripts!
This is your problem. How do you use the mean function, for example? You call it in a line of code, like this:
xmean = mean(1:5);
You don't ever use the run button on mean itself, or on ANY function written by yourself or any function provided in MATLAB. Again, you don't seem to understand functions, and how they are different from scripts. You need to spend some time appreciating that fundamental difference.
Sadiq
on 24 Dec 2023
You can
write a script that gives values to the input arguments of a function and call the function with these inputs or
write a script that gives values to the input arguments of a function, call the function with these inputs and reset the inputs inside the function
You can't
call a function without giving values to all its input arguments, neither in part nor in total.
I suggest you spend 2 hours of your time to pass an introductory course free of costs to learn about the MATLAB basics:
Sadiq
on 24 Dec 2023
Look at the first executable line in NBA1:
If this function is called with no input arguments (if nargin < 1), all the necessary parameters of the input list are set in the if-statement, and the function will work.
To tell why NBA22 does not work, you will have to tell us which values you supplied for the input parameters. The following should work (of course you have to include your objective function "fobj1" somewhere):
% Supply values for all the input arguments to NBA22
FitFunc = @fobj1;
iter = 1000;
pop = 30;
dim = 4;
lb= 0 * ones( 1,dim ); % Lower bounds
ub= [5*ones( 1,dim/2 ) 90*ones(1,dim/2)]; % Upper bounds
% Call the function
[ bestX, fMin, time ] = NBA22( FitFunc, iter, pop, dim,lb,ub)
function [ bestX, fMin, time ] = NBA22( FitFunc, iter, pop, dim,lb,ub)
tic;
% Display help
% help NBA.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set the default parameters
% if nargin < 1
% 1)The parameters in the basic Bat Algorithm (BA)
FitFunc = FitFunc; % @Sphere;
M = iter;%1000;
pop = pop;%30;
dim = dim;%4;%20;
gamma = 0.9;
alpha = 0.99;
r0Max = 1;
r0Min = 0;
AMax = 2;
AMin = 1;
freqDMax = 1.5;
freqDMin = 0;
% 2)The additional parameters in Novel Bat Algorithm (NBA)
G = 10;
probMax = 0.9;
probMin = 0.6;
thetaMax = 1;
thetaMin = 0.5;
wMax = 0.9;
wMin = 0.5;
CMax = 0.9;
CMin = 0.1;
% end
% set the parameters
%lb= 0 * ones( 1,dim ); % Lower bounds
lb=lb; % Lower bounds
%ub= [5*ones( 1,dim/2 ) 90*ones(1,dim/2)]; % Upper bounds
ub= ub;%[5*ones( 1,dim/2 ) 90*ones(1,dim/2)]; % Upper bounds
vLb = 0.6 * lb;
vUb = 0.6 * ub;
r = rand( pop, 1 ) .* 0.2 + 0;
r0 = rand( pop, 1 ) .* ( r0Max - r0Min ) + r0Min;
A = rand( pop, 1 ) .* ( AMax - AMin ) + AMin;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Initialization
for i = 1 : pop
x( i, : ) = lb + (ub - lb) .* rand( 1, dim );
v( i, : ) = rand( 1, dim );
fit( i ) = FitFunc( x( i, : ) );
end
pFit = fit; % The individual's best fitness value
pX = x; % The individual's best position corresponding to the pFit
[ fMin, bestIndex ] = min( fit ); % fMin denotes the global optimum
% bestX denotes the position corresponding to fMin
bestX = x( bestIndex, : );
bestIter = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Start the iteration.
for iteration = 1 : M
% The compensation rates for Doppler effect in echoes
C = rand( pop, 1 ) .* ( CMax - CMin ) + CMin;
% The probability of habitat selection
prob = rand( pop, 1 ) .* ( probMax - probMin ) + probMin;
% Contraction¨Cexpansion coefficient
theta=( thetaMax - thetaMin ) * ( M - iteration )/(1.0 * M) + thetaMin;
freqD = rand( pop, dim ) .* ( freqDMax - freqDMin ) + freqDMin;
w = (wMax - wMin) * ( M - iteration )/(1.0 * M) + wMin; %Inertia weight
meanP = mean( pX );
meanA = mean( A );
for i = 1 : pop
if rand < prob
if rand < 0.5
x( i, : ) = bestX + theta * abs( meanP - pX(i, :) ) *...
log( 1.0/rand );
else
x( i, : ) = bestX - theta * abs( meanP - pX(i, :) ) *...
log( 1.0/rand );
end
else
freqD( i, :) = freqD(i, :) .* ( 340 + v( i, : ) )./( 340 + ...
v( bestIndex, : ) + realmin );
v( i, : ) = w .* v( i, : ) + ( bestX - pX(i, :) ) .* ...
freqD(i,:) .* ( 1 + C(i) .* ( bestX - pX(i, :) ) ./...
( abs( bestX - pX(i, :) ) + realmin ) );
v( i, : ) = Bounds( v( i, : ), vLb, vUb );
x( i, : ) = x( i, : ) + v( i, : );
end
% Local search
if rand > r( i )
randnValueA = randn( 1,dim ).* ( abs( A(i) - meanA )+ realmin);
x( i, : ) = bestX .* ( 1 + randnValueA );
end
x( i, : ) = Bounds( x( i, : ), lb, ub );
fit( i ) = FitFunc( x( i, : ) );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Update the individual's best fitness vlaue and the global best one
for i = 1 : pop
if fit( i ) < pFit( i )
pFit( i ) = fit( i );
pX( i, : ) = x( i, : );
end
if( pFit( i ) < fMin && rand < A(i) )
fMin = pFit( i );
bestX = pX( i, : );
bestIndex = i;
bestIter = iteration;
A(i) = A(i) * alpha;
r(i) = r0(i) * ( 1 - exp( -gamma * iteration ) );
end
end
if( iteration - bestIter > G )
r = rand( pop, 1 ) .* 0.05 + 0.85;
A = rand( pop, 1 ) .* ( AMax - AMin ) + AMin;
end
time=toc;% By Me
end
end
% End of the main program
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The following functions are associated with the main program
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Application of simple limits/bounds
function s = Bounds( s, Lb, Ub)
% Apply the lower bound vector
temp = s;
I = temp < Lb;
temp(I) = Lb(I);
% Apply the upper bound vector
J = temp > Ub;
temp(J) = Ub(J);
% Update this new move
s = temp;
end
Sadiq
on 25 Dec 2023
Dyuman Joshi
on 25 Dec 2023
@Sadiq, see the first if condition statement (line 8 to line 33) in NBA1 - It checks if the number of inputs provided are less than 1 (i.e. no inputs are provided) or not. If they are less than 1, the statement defines the values to be used.
That is not a good check, but we'll dive into that later.
So, when you press the green button, MATLAB calls the function without any input, thus the if condition is triggered and the code runs accordingly.
And as you have not specified any output variables, the output is given as ans.
Also, you should not run a function using the Green colored Run button. You should call it - using the function name, providing inputs and specifying outputs.
Hi @Sadiq
I've provided the necessary inputs for the Novel Bat Algorithm function. It will return the optimal values, bestX, for the problem, and the minimum value (fMin) of the objective function at bestX. You can execute the code by either entering it directly into the Command Window (between the 'Start' and 'End' of Script), or by creating a new script file. Copy and paste the code into the new file, save it as 'myNBAscript.m' in the same folder as NBA1.m and fobj1.m, and then click the 'Run' button
.
%% ------ Start of Script ------
% User-supplied inputs (objective function and the rest of undefined hyperparameters)
FitFunc = @fobj1; % handle for objective function 'fobj1()'
M = 1000; % I guess this is the number of iterations
pop = 30; % I guess this is the number of populations
dim = 4; % I guess this is the number of variables
G = 10;
gamma = 0.9;
alpha = 0.99;
r0Max = 1;
r0Min = 0;
AMax = 2;
AMin = 1;
freqDMax = 1.5;
freqDMin = 0;
probMax = 0.9;
probMin = 0.6;
thetaMax = 1;
thetaMin = 0.5;
wMax = 0.9;
wMin = 0.5;
CMax = 0.9;
CMin = 0.1;
% Call the so-called "Novel" Bat Optimizer
[bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
%% ------ End of Script ------
%% Novel Bat Algorithm (1st function file called 'NBA1.m')
function [bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
% Display help
% help NBA.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set the default parameters
if nargin < 1
% 1) The parameters in the basic Bat Algorithm (BA)
FitFunc = @fobj1; % @Sphere;
M = 1000;
pop = 30;
dim = 4; %20;
gamma = 0.9;
alpha = 0.99;
r0Max = 1;
r0Min = 0;
AMax = 2;
AMin = 1;
freqDMax = 1.5;
freqDMin = 0;
% 2) The additional parameters in Novel Bat Algorithm (NBA)
G = 10;
probMax = 0.9;
probMin = 0.6;
thetaMax = 1;
thetaMin = 0.5;
wMax = 0.9;
wMin = 0.5;
CMax = 0.9;
CMin = 0.1;
end
% set the parameters
lb = 0*ones(1, dim); % Lower bounds
ub = [5*ones(1, dim/2) 90*ones(1, dim/2)]; % Upper bounds
vLb = 0.6*lb;
vUb = 0.6*ub;
r = rand( pop, 1 ) .* 0.2 + 0;
r0 = rand( pop, 1 ) .* ( r0Max - r0Min ) + r0Min;
A = rand( pop, 1 ) .* ( AMax - AMin ) + AMin;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Initialization
for i = 1 : pop
x( i, : ) = lb + (ub - lb) .* rand( 1, dim );
v( i, : ) = rand( 1, dim );
fit( i ) = FitFunc( x( i, : ) );
end
pFit = fit; % The individual's best fitness value
pX = x; % The individual's best position corresponding to the pFit
[ fMin, bestIndex ] = min( fit ); % fMin denotes the global optimum
% bestX denotes the position corresponding to fMin
bestX = x( bestIndex, : );
bestIter = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Start the iteration.
for iteration = 1 : M
% The compensation rates for Doppler effect in echoes
C = rand( pop, 1 ) .* ( CMax - CMin ) + CMin;
% The probability of habitat selection
prob = rand( pop, 1 ) .* ( probMax - probMin ) + probMin;
% Contraction¨Cexpansion coefficient
theta=( thetaMax - thetaMin ) * ( M - iteration )/(1.0 * M) + thetaMin;
freqD = rand( pop, dim ) .* ( freqDMax - freqDMin ) + freqDMin;
w = (wMax - wMin) * ( M - iteration )/(1.0 * M) + wMin; %Inertia weight
meanP = mean( pX );
meanA = mean( A );
for i = 1 : pop
if rand < prob
if rand < 0.5
x( i, : ) = bestX + theta * abs( meanP - pX(i, :) ) *...
log( 1.0/rand );
else
x( i, : ) = bestX - theta * abs( meanP - pX(i, :) ) *...
log( 1.0/rand );
end
else
freqD( i, :) = freqD(i, :) .* ( 340 + v( i, : ) )./( 340 + ...
v( bestIndex, : ) + realmin );
v( i, : ) = w .* v( i, : ) + ( bestX - pX(i, :) ) .* ...
freqD(i,:) .* ( 1 + C(i) .* ( bestX - pX(i, :) ) ./...
( abs( bestX - pX(i, :) ) + realmin ) );
v( i, : ) = Bounds( v( i, : ), vLb, vUb );
x( i, : ) = x( i, : ) + v( i, : );
end
% Local search
if rand > r( i )
randnValueA = randn( 1,dim ).* ( abs( A(i) - meanA )+ realmin);
x( i, : ) = bestX .* ( 1 + randnValueA );
end
x( i, : ) = Bounds( x( i, : ), lb, ub );
fit( i ) = FitFunc( x( i, : ) );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Update the individual's best fitness vlaue and the global best one
for i = 1 : pop
if fit( i ) < pFit( i )
pFit( i ) = fit( i );
pX( i, : ) = x( i, : );
end
if( pFit( i ) < fMin && rand < A(i) )
fMin = pFit( i );
bestX = pX( i, : );
bestIndex = i;
bestIter = iteration;
A(i) = A(i) * alpha;
r(i) = r0(i) * ( 1 - exp( -gamma * iteration ) );
end
end
if( iteration - bestIter > G )
r = rand( pop, 1 ) .* 0.05 + 0.85;
A = rand( pop, 1 ) .* ( AMax - AMin ) + AMin;
end
end
end % <-- put 'end' here
% End of the main program <-- for NBA only
%% A function for 'Bounds' (a local function embedded in NBA1() function file)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The following functions are associated with the main program
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Application of simple limits/bounds
function s = Bounds(s, Lb, Ub)
% Apply the lower bound vector
temp = s;
I = temp < Lb;
temp(I) = Lb(I);
% Apply the upper bound vector
J = temp > Ub;
temp(J) = Ub(J);
% Update this new move
s = temp;
end % <-- put 'end' here
%% Objective Function (2nd function file called 'fobj1.m')
function e = fobj1(b)
u = [2 5 30 50];
[R, C] = size(b);
P = C/2;
M = 2*C;
k = (-(M/2-1):M/2).';
i = (1:P);
xo = sum(1*exp(1i*((k).*(-pi/2).*sind(u(P+i))+((k).^2.*pi./(16*u(i))).*cosd(u(P+i)).^2)),2);
xe = sum(1*exp(1i*((k).*(-pi/2).*sind(b(P+i))+((k).^2.*pi./(16*b(i))).*cosd(b(P+i)).^2)),2);
%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%
e = norm(xo - xe).^2/(M);
end % <-- put 'end' here
4 Comments
Sadiq
on 25 Dec 2023
Torsten
on 25 Dec 2023
And what do you get as fMin after the second run ?
I see. The objective function probably has one global minimum and one local minimum. To assess convergence, you should run the Novel Bat Algorithm (NBA) multiple times. It's important to note that metaheuristic optimizers do not guarantee finding the global minimum.
%% ------ Start of Script ------
% Call NBA 1st time
[bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
% Call NBA 2nd time
[bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
% Call NBA 3rd time
[bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
% Call NBA 4th time
[bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
% Call NBA 5th time
[bestX, fMin] = NBA1(FitFunc, M, pop, dim, G, gamma, alpha, r0Max, r0Min, AMax, AMin, freqDMax, freqDMin, probMax, probMin, CMax, CMin, thetaMax, thetaMin, wMax, wMin)
%% ------ End of Script ------
Sadiq
on 25 Dec 2023
Categories
Find more on Elementary Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!