Matlab: stop terminal message in call to ga (genetic algorithm function) - matlab

In matalb I am implementing genetic algorithm using ga. In a typical call to ga like x = ga(nvars,#fitnessfunc) when returns gives message on terminal specifying the reason for the termination of the genetic algorithm. A typical message is:
Optimization terminated: average change in the fitness value less than options.TolFun.
I want to turn off this message. I read the documentation but found nothing.
Any ideas?

You could try the answer given in here.
Use the evalc and then you wont display the text plus you can actually read it and use it for your own purposes (like knowing why did it stop etc)

Found the answer here minutes after posting the question. To stop the display we have to set display parameter of options structure to 'off'. The proper code is below:
problem.solver = 'ga';
problem.options = gaoptimset('display','off','param2','value2'...);
problem.fitnessfnc = #fitness;
problem.nvars = nvars;
output = ga(problem);

Related

How can I stop matlab pde solver in pde tool box when solution is unstable

I am solving two coupled time dependent PDE eqations using pde tool box.The simulation box size is x=6 and y=10.Currently I solve it properly and acces the solution data using
results = solvepde(model,tlist); u = results.NodalSolution(:,1,:);
What I need to do is now to stop the code when the solution u is unstable along the y axis.That means I want to monitor solution of u along y axis while running the code and stop it when it meets a criteria that I want.(For example I want to stop the code when solution of u along y equals to 0)..How can I do it using pde tool box?
Here is what I tried so far.Is there easy way to access the results while code is running?.That is I want to access the solution for each time step.
%calculate solutions
n=4000;
tlist = linspace(0,200,n);
partial=zeros(49,1);
for i=1:n
results = solvepde(model,tlist(i:i+1));
u = results.NodalSolution(:,1,1);
v=results.NodalSolution(:,2,1);
u1=results.NodalSolution(113:161,1,1);
u2=results.NodalSolution(1,1,1);
u3=results.NodalSolution(4,1,1);
for j=1:49
partial(j)=u1(j)-0.5*u2-0.5*u3;
end
sigma=sum(partial);
if sigma>1e-4
disp('verified')
return
end
end
There are several ways to stop a code during execution:
keyboard
Using this function stops the execution and gives you access to the keyboard, such that you can see all values.
warning('Solution is unstable')
This won't actually stop the code but will give you a warning stating that the solution is unstable.
error('Solution is unstable')
This will actually stop the code, giving you the error, that the solution is unstable.
break
This will not give you any feedback, but it will stop the for-loop and then continue the rest of the code.
In all cases you include the way of stopping the code in an if-statement, like
if (all(u==0))
*statement from above*
end

Using if function in MATLAB Simulink

I have created the following block diagram on Matlab Simulink. It should give OUT1=1 OUT2=0 when INPUT>=0 and OUT1=0 OUT2=1 when INPUT<0. But it does not give the expected results. What is the reason for that. Any advice to make it work correctly would be appreciated.
The behaviour you are seeing can be explained by noting the following:
The output from the If Subsystem acts like an enable signal.
By default, the Output Ports of an If Action Subsystem are set to hold their values when the (sub)system is disabled.
This can be changed by going to the parameters dialog of the Output Port (within the If Action Subsystems) and changing the Output when disabled property to reset. You'll also want to change the default value to zero.
In many cases an IF is translated to a switch. You calculate cases and select the one which is intended. Here you could connect a constant [1 0] and a constant [0 1] to the first and third input and the sign block from your solution to the second input.
This if function block thing didn't work. So I come up with a different approach to get the result I wanted using the sign block. Solution is posted below. Thank you for everyone for trying to help.

Is it possible to enforce input argument data types in MATLAB?

I would like to ensure that the input arguments to a user-defined MATLAB function (contained in an m-file) are of a certain type. I understand that MATLAB automatically assigns data types to variables (to the liking of some and the dismay of others), but I would like to know if there is an option of "strict data typing" in MATLAB, or something of the sort, especially for input arguments for a user-defined function.
I found a helpful explanation of MATLAB's "fundamental classes" (data types) at these two webpages:
http://www.mathworks.com/help/matlab/matlab_prog/fundamental-matlab-classes.html
http://www.mathworks.com/help/matlab/data-types_data-types.html
However, I have been unable to find an answer to the question of strict data typing, particularly for function input arguments. I thought it would be a pretty basic question that already had been answered in numerous places, but after extensive searching I have not yet found a conclusive answer. For now, I have been manually checking the data type using the is[TYPE]() functions and displaying an error message if it does not comply, though this seems sloppy and I wish I could just get MATLAB to enforce it for me.
Below is an example of a function in which I would like to specify the input argument data type. It resides in a file called strict_data_type_test.m in MATLAB's current path. In this function, I would like to force the variable yes_or_no to be of MATLAB's logical data type. I know I can use the islogical() function to manually check, but my question is if it is possible to have MATLAB enforce it for me. I also know that any non-zero double evaluates to true and a zero evaluates to false, but I want to force the user to send a logical to make sure the wrong argument was not sent in by accident, for example. Here is the example function:
function y = strict_data_type_test( x, yes_or_no )
% manual data type check can go here, but manual check is not desirable
if (yes_or_no)
y = 2 .* x;
else
y = -5 .* x;
end
end
Adding the data type before the input argument variable name (like in most programming languages) treats the data type text as another variable name instead of a data type identifier. From that it would seem that strict data typing is not possible in MATLAB by any means, but maybe one of you many gurus knows a useful trick, feature, or syntax that I have not been able to find.
validateattributes might also work for you, if there is an appropriate attribute for your case. For example if you want to enforce that yes_or_no is a logical scalar, you could try:
validateattributes(yes_or_no,{'logical'},{'scalar'})
Otherwise maybe an attribute like 'nonempty'.
I've gotten some great responses so I can't pick just one as the "accepted answer", but to summarize what I've learned from you all so far:
No, MATLAB does not have built-in strict data typing for function input arguments
MATLAB compiles the code before running, so manual validation checking should not be very taxing on performance (the profiler can be used to assess this)
Many helpful methods of doing the manual validation checking exist, listed here in order of most relevant to least relevant for what I was trying to do:
inputParser class
validateattributes()
Error/exception handling (throw(), error(), assert(), etc.)
MATLAB's built-in state detection functions (a.k.a predicate functions)
I can look through some MathWorks-provided MATLAB functions (or Statistics toolbox functions) for ideas on how to validate input arguments by typing edit followed by the function name. Two suggested functions to look at are normpdf() (from the Statistics toolbox) and integral(). Some other functions I found helpful to look at are dot() and cross().
Other thoughts:
It would appear that the inputParser class was the overall concensus on the most professional way to validate input arguments. It was noted on a related (but not duplicate) stackoverflow post that the newer MathWorks functions tend to make use of this class, suggesting that it may be the best and most up-to-date choice.
Since the MathWorks-provided MATLAB functions do not appear to enforce strict input argument data typing, this further suggests that even if it was possible to do so, it may not be a recommended approach.
MATLAB seems to regard "error handling" and "exception handling" as two different concepts. For example, here are two links to MATLAB's Documentation Center that show how MathWorks considers "error handling" and "exception handling" differently: MathWorks Documentation Center article on Error Handling, MathWorks Documentation Center article on Exception Handling. A relevant StackOverflow post has been made on this topic and can be found here (link). I contacted MathWorks and added some new information about this topic to that post, so if you are interested you may read more by following that link.
Matlab provides an 'inputParser' which allows to check inputs. Besides this you can use assertions:
assert(islogical(yes_or_no),'logical input expected')
To ensure the correct number of input arguments, use narginchk.
btw: Take a look in some Matlab functions like edit integral and check how tmw deals with this.
You may find writing this sort of code tedious or worry that it degrades performance:
if ~islogical(yes_or_no) && ~isscalar(yes_or_no)
error('test:NotLogicalType','Second argument must be logical (Boolean).');
end
if yes_or_no
y = 2 .* x;
else
y = -5 .* x;
end
Recall, however, that Matlab compiles the code before running so even if you need to test many conditions it will be quite fast. Run the profiler to see.
Another option in some cases (maybe not your example) is to use a lazier method. This option lets your code run with whatever inputs were provided, but uses a try/catch block to trap any error:
try
if yes_or_no
y = 2 .* x;
else
y = -5 .* x;
end
catch me
...
error('test:NotLogicalType','Second argument must be logical (Boolean).');
% rethrow(me);
end
The code above would produce an error if yes_or_no was a cell array for example (it will still allow non-Boolean, non-scalar, etc. values for yes_or_no though, but Matlab is often overly permissive). You can then either generate a custom error message, detect, what kind of error was thrown and try something else, etc. Many of the functions in the Statistics toolbox use this approach (e.g., type edit normpdf in your command window) for better or worse.

Getting the solver type and step size (for fixed step solvers)

we are trying to integrate a simulation model into Simulink as a block. We have a custom continuous block which loads an m file that contains the functions Derivatives, Outputs etc.
My question is: is there a way to find out which solver is used currently and with which parameters? Our model won't be able to support variable time solvers and I would like to give a warning. Similarly, the model requires the fixed step time for initialization.
Thanks in advance.
You can get the current solver name using
get_param('modelName', 'SolverName');
Some of the other common solver parameters are
AbsTol
FixedStep
InitialStep
ZcThreshold
ExtrapolationOrder
MaxStep
MinStep
RelTol
SolverMode
You can find other parameters you may wish to query by opening the .mdl file in your favorite text editor and digging through it.
If I'm understanding your use case correctly, you are trying to determine the type of solver (and other solver params) for the top-level simulink system containing your block.
I think the following should give you what you want:
get_param(bdroot, 'SolverType'); % //Returns 'Variable-step' or 'Fixed-step'
get_param(bdroot, 'FixedStep'); % //Returns the fixed step size
Notice that for purposes of generality/reusability, this uses bdroot to identify the top-level system (rather than explicitly specifying the name of this system).
If you want to find out more about other model parameters that you can get/set, I would check out this doc.
Additionally, I'm interested to know why it is that your model doesn't support a variable-step solver?

Numerical problems in Matlab: Same input, same code -> different output?

I am experiencing problems when I compare results from different runs of my Matlab software with the same input. To narrow the problem, I did the following:
save all relevant variables using Matlab's save() method
call a method which calculates something
save all relevant output variables again using save()
Without changing the called method, I did another run with
load the variables saved above and compare with the current input variables using isequal()
call my method again with the current input variables
load the out variables saved above and compare.
I can't believe the comparison in the last "line" detects slight differences. The calculations include single and double precision numbers, the error is in the magnitude of 1e-10 (the output is a double number).
The only possible explanation I could imagine is that either Matlab looses some precision when saving the variables (which I consider very unlikely, I use the default binary Matlab format) or that there are calculations included like a=b+c+d, which can be calculated as a=(b+c)+d or a=b+(c+d) which might lead to numerical differences.
Do you know what might be the reason for the observations described above?
Thanks a lot!
it really seems to be caused by the single/double mix in the calculations. Since I have switched to double precision only, the problem did not occur anymore. Thanks to everybody for your thoughts.
these could be rounding errors. you can find the floating point accuracy of you system like so:
>> eps('single')
ans =
1.1921e-07
On my system this reports 10^-7 which would explain discrepancies of your order
To ensure reproducible results, especially if you are using any random generating functions (either directly or indirectly), you should restore the same state at the beginning of each run:
%# save state (do this once)
defaultStream = RandStream.getDefaultStream;
savedState = defaultStream.State;
save rndStream.mat savedState
%# load state (do this at before each run)
load rndStream.mat savedState
defaultStream = RandStream.getDefaultStream();
defaultStream.State = savedState;