Matlab set range of inputs and step - matlab

I have this signal:
x(t) = t*sin(m*pi*t)*heaviside(-m*pi-t)+t*cos(k*pi*t)*heaviside(t-k*pi)+sin(k*pi*t)*cos(m*pi*t)*(heaviside(t+m*pi)-heaviside(t-k*pi));
and I want to calculate the values only from -5pi to 5pi with a step of pi/100 using Matlab. How could I do it?

Provided you have defined m and k somewhere, and you have the matlab symbolic toolbox which provides the heaviside function, this is how it is done:
% First we define the function
x = #(t) t*sin(m*pi*t)*heaviside(-m*pi-t)+t*cos(k*pi*t)*heaviside(t-k*pi)+sin(k*pi*t)*cos(m*pi*t)*(heaviside(t+m*pi)-heaviside(t-k*pi));
% Then we define the values for which we want to compute the function
t_values = -5*pi:pi/100:5*pi;
% Finally we evaluate the function
x_values = x(t_values)
Details
First line we define your function as an anonymous function which is a handy tool in matlab.
Then we create a vector of values from -5pi to 5*pi with steps of pi/100. For this we use the matlab colon syntax. It makes it short and efficient.
Finally we evaluate the function on each of the t_values by passing the vector to the anonymous function.
Note: If you don't have the symbolic toolbox, you could easily implement heaviside yourself.

Related

How to set up solving of multiple ODEs in Matlab propperly?

I have a task of writing an M script that would set up (and finally solve) a set of 19 differential equations and all of the equation coefficients. I am not sure what is the best way to input those equations.
Example of some equations:
Example of coefficients:
I don't think that this would be suited for Simulink. Other examples use a function in the form of #(t,x) where t is time and x the vector of all variables.
There are loads of "examples" online, but they don't seem to be appropriate for such a large set of large equations.
For example this exmple of solving 3 equatons
Even for 3 simple equations as they have solved, the functions are getting messy:
f = #(t,x) [-x(1)+3*x(3);-x(2)+2*x(3);x(1)^2-2*x(3)];
Using this notation and getting to the x(19) and cross-referencing all instances of x would be a mess.
I would like your help, and a simple example of how could I write these equations line by line, maybe using the symbolic toolbox, and then put them in an array that I can then forward to the solver.
As I said, I know there are examples online, but they tackle only the most basic system, and really they don't scale well if you want a clean and easily readable code.
I would like to have a similar to Wolfram alpha, where you type variable names as they are (instead od x(1), x(2), ... m x(19)) and if it's possible to get all solution vectors with their variable names.
You don't have to use an anonymous function handle as an ode function, you can create a separate function file (as shown in the odefun section of ode45.
For example, your odefun can look like:
function dy = myode(t,y)
% first unpack state variables
i_d2 = y(1);
i_q2 = y(2);
...
gamma2 = y(end-1);
omega2 = y(end);
% determine all constants
c34 = expression_for_c34;
...
c61 = expression_for_61;
% determine state derivative
i_d2_dot = expression;
...
omega2_dot = expression;
% pack state derivative based on order in state vector
dy(1) = i_d2_dot;
...
dy(end) = omega2_dot;
end
From this myode function you can also call other functions to e.g. determine the value for some coefficients based on the current state. Next, integrate the system using a suitable ode solver:
[t,y] = ode45(#myode,tspan,y0);

Minimizing Function with vector valued input in MATLAB

I want to minimize a function like below:
Here, n can be 5,10,50 etc. I want to use Matlab and want to use Gradient Descent and Quasi-Newton Method with BFGS update to solve this problem along with backtracking line search. I am a novice in Matlab. Can anyone help, please? I can find a solution for a similar problem in that link: https://www.mathworks.com/help/optim/ug/unconstrained-nonlinear-optimization-algorithms.html .
But, I really don't know how to create a vector-valued function in Matlab (in my case input x can be an n-dimensional vector).
You will have to make quite a leap to get where you want to be -- may I suggest to go through some basic tutorial first in order to digest basic MATLAB syntax and concepts? Another useful read is the very basic example to unconstrained optimization in the documentation. However, the answer to your question touches only basic syntax, so we can go through it quickly nevertheless.
The absolute minimum to invoke the unconstraint nonlinear optimization algorithms of the Optimization Toolbox is the formulation of an objective function. That function is supposed to return the function value f of your function at any given point x, and in your case it reads
function f = objfun(x)
f = sum(100 * (x(2:end) - x(1:end-1).^2).^2 + (1 - x(1:end-1)).^2);
end
Notice that
we select the indiviual components of the x vector by matrix indexing, and that
the .^ notation effects that the operand is to be squared elementwise.
For simplicity, save this function to a file objfun.m in your current working directory, so that you have it available from the command window.
Now all you have to do is to call the appropriate optimization algorithm, say, the quasi Newton method, from the command window:
n = 10; % Use n variables
options = optimoptions(#fminunc,'Algorithm','quasi-newton'); % Use QM method
x0 = rand(n,1); % Random starting guess
[x,fval,exitflag] = fminunc(#objfun, x0, options); % Solve!
fprintf('Final objval=%.2e, exitflag=%d\n', fval, exitflag);
On my machine I see that the algorithm converges:
Local minimum found.
Optimization completed because the size of the gradient is less than
the default value of the optimality tolerance.
Final objval=5.57e-11, exitflag=1

fmincon optimization with defined Matlab function

Is it possible to use the optimization function fmincon with a Matlab defined function?
I wrote a function where I give few constant parameters (real or complex) and for now, every time I change these parameters, the result changes (you don't say).
[output1, output2] = my_function(input1,input2,input3,input4)
I saw that fmincon function allows to find the optimum result with a given constraint. Let's say that I want to find the optimum output acting only on input1 and keeping constant all the others inputs. Is it possible to define something like
fmincon(#(input1)my_function,[1,2],[],mean)
for input1 that goes from 1 to 2 for the best value mean, where mean is the mean value of some other results.
I know that is a quite vague question but I'm not able to give a minimum example, since function makes a lot of things
The first attept with multiple outputs gave me the error Only functions can return multiple values.
Then I tried with only one output and if I use
output1 = #(input1)function(input2,input3);
fmincon(#output1,[1,2],[],mean)
I get the error
Error: "output1" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
With fmincon(#my_function,[1,2],[],mean) I get Not enough input arguments.
The input should be used in your function definition - read up on how anonymous functions should be written. You don't have to use anonymous functions to define the actual objective function (myFunction below), you can use functions in their own file. The key is that the objective function should return a scalar to be minimised.
Here is a very simple example, using fmincon to find the minima in myFunction, based on the initial guess [1.5,1.5].
% myFunction is min when x=1,y=2
myFunction = #(x,y) (x-1).^2 + (y-2).^2;
% Define the optimisation function.
% This should take one input (can be an array)
% and output a scalar to be minimised
optimFunc = #(P) myFunction( P(1), P(2) );
% Use fmincon to find the optimum solution, based on some initial guess
optimSoln = fmincon( optimFunc, [1.5, 1.5] );
% >> optimSoln
% optimSoln =
% 0.999999990065893 1.999999988824129
% Optimal x = optimSoln(1), optimal y = optimSoln(2);
You can see the calculated optimum isn't exactly [1,2], but it's within the default optimality tolerance. You can change the options for the fmincon solver - read the documentation.
If you wanted to keep y=1 as a constant, you just need to update the function definition:
% We only want solutions with y=1
optimFunc_y1 = #(P) myFunction( P(1), 1 ); % y=1 always
% Find new optimal solution
optimSoln_y1 = fmincon( optimFunc_y1, 1.5 );
% >> optimSoln_y1
% optimSoln_y1 =
% 0.999999990065893
% Optimal x when y=1 = optimSoln(1)
You can add inequality constraints using the A, B, Aeq and Beq inputs to fmincon, but that's too broad to go into here, please refer to the docs.
Note that you're using the keyword function in a way which is invalid syntax. I've instead used valid variable names for the functions in my demo.

How to display parameter values at every iteration while using Genetic algorithm in matlab

I am using GA to solve for 6 parameters using the global optimization toolbox.
Is there a way to display the parameter values at every iteration of GA. I can use display or iter but it doesn't necessarily display the parameter values.
Thank you
You can use plot functions.
You can either use one of the predefined plot functions:
options = gaoptimset('PlotFcns',#gaplotbestf);
x= ga(#f,6,[],[],[],[],[],[],[],options)
or you can write your own. For example:
function gademo
options= gaoptimset('PlotFcns',#myplot,'PopulationSize',10);
x= ga(#f,6,[],[],[],[],[],[],[],options)
function y= f(x) % the fitness function
y= norm(x);
end
% simple plot function
function state= myplot(options,state,flag)
fprintf('generation number: %d\n',state.Generation);
fprintf('population:\n');
disp(state.Population);
end
end
Have you tried using the function fprintf?
For example, if you wanted to print the first element of vector x, which is a float, to the screen:
fprintf(1,'%f\n', x(1))
You can see how to format numbers and strings in the documentation of fprintf if you scroll down a bit under formatSpec.

Differentiation with respect to a self-defined function in matlab

I have made a function in func.m which is defined as follows:
function f = func(b)
f = b^2+1;
end
now i wish to differentiate with respect to that function i.e.
find 2*b+1 with a given value for b (lets say 1)
I tried diff(func(1)) but it returned an empty matrix.
Any ideas?
thanks
Your input argument func(1) is a vector of size 1x1. The function diff caled on vectors is this one: here. If you want to use the symbolic one, which allows to differentiate a function but requires the symbolic toolbox, you have to use a symbolic input. Explained here
Example:
% create a symbolic variable x
syms x
%differentiate f(x) and name it f1(x)
f1(x)=diff(f(x))
%get the value at point 1
f1(1)
If you don't have the symbolic toolbox, there is also a numeric solution.