Clear Filters
Clear Filters

How to locate the answer in the given code?

1 view (last 30 days)
Sadiq
Sadiq on 24 Dec 2023
Commented: Sadiq on 25 Dec 2023
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
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
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.
I suggest you go through these - nargin, Find Number of Function Arguments

Sign in to comment.

Answers (2)

John D'Errico
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)
ans = 3
whos
Name Size Bytes Class Attributes ans 1x1 8 double
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)
xmean = 3
whos
Name Size Bytes Class Attributes xmean 1x1 8 double
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
Name Size Bytes Class Attributes ans 1x1 8 double
So now I have intentionally created a variable named ans. But then I'll use mean, again with no output assigned.
mean(1:5)
ans = 3
whos
Name Size Bytes Class Attributes ans 1x1 8 double
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
Sadiq on 25 Dec 2023
Thanks a lot dear Torsten for your kind response. Ok just comment the line
if nargin < 1
with the end statement on line 32 i.e.,
% end
So the function becomes like the following:
function [ bestX, fMin, time ] = NBA22( fobj1Mathworks, 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 = @fobj1Mathworks; % @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
% 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 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;
Now if you press the "Run buttob", it will run and will give you the result also even though the statment
if narg < 1
has been commented and the values of the input arguments are not supplied before the function definition.
But if you copy the 1st line of the same function without key word function i.e.,
[ bestX, fMin, time ] = NBA22( fobj1Mathworks, iter, pop, dim,lb,ub)
and paste it in the command window, and press the enter key, it will give you the following error i.e.,
Unrecognized function or variable 'iter'.
Dyuman Joshi
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.
I suggest you go through these - nargin, Find Number of Function Arguments

Sign in to comment.


Sam Chak
Sam Chak on 25 Dec 2023
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)
bestX = 1×4
5.0000 2.0000 50.0000 30.0000
fMin = 9.0442e-31
%% ------ 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
Sam Chak
Sam Chak on 25 Dec 2023
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)
bestX = 1×4
2 5 30 50
fMin = 0
% 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)
bestX = 1×4
5.0000 2.0000 50.0000 30.0000
fMin = 2.4049e-27
% 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)
bestX = 1×4
5.0000 2.0000 50.0000 30.0000
fMin = 4.9342e-31
% 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)
bestX = 1×4
2.0000 5.0000 30.0000 50.0000
fMin = 1.3867e-31
% 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)
bestX = 1×4
2.0000 5.0000 30.0000 50.0000
fMin = 4.0927e-28
%% ------ End of Script ------
Sadiq
Sadiq on 25 Dec 2023
I get differnt values of fMin each time. But what is the relation of that with this swapping?
Yes, ofcourse that is what I am saying. So what will we do to avoid swapping the result?

Sign in to comment.

Categories

Find more on Data Type Identification 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!