Having errors with userdefined functions - matlab

Doing homework and there's a question that's giving me trouble. The questions is:
a)create a function M-file called nmoles that requires two vector inputs—
the mass and molecular weight—and returns the corresponding number
of moles. Because you are providing vector input, it will be necessary
to use the meshgrid function in your calculations.
b) Test your function for the compounds shown in the following table, for
masses from 1 to 10 g:
In my function file, i've got:
function [ n ] = nmoles(m, MW)
%% Finds number of moles
m = (1:10); %% mass range
MW = [78.115 46.07 102.3]; %% Values from the table
n=m/MW; %%formula provided by the textbook
My main file only has:
nmoles(m,MW)
I'm getting an error: "Error using / Matrix dimensions must agree"
Also: Error in nmoles (line 10) n=m/MW;
I'm inexperienced with MATLAB and still learning syntax but I assume that my formula is incorrect and i'm using the wrong symbol to divide, though i'm not sure how to correct this. Also, how would i incorporate the meshgrid function into my anwser?

Here is how your function should probably look like:
function [ n ] = nmoles(m, MW)
% Finds number of moles
[mv,MWv] = meshgrid(m, MW); % extends m and MW to match all combinations.
n = mv./MWv; %formula provided by the textbook
end
And then your main script should be:
m = 1:10; % mass range
MW = [78.115 46.07 102.3]; % Values from the table
nmoles(m, MW)
You had 3 mistakes:
If you get m and MW as input to the function, your not suppose to define them within it.
Because you want the number of moles for each combination of mass and molar weight, you use meshgrid.
When you want to perform an elementwise division or multiplication on 2 arrays, put a . before the / or *. In MATLAB everything is a matrix by default, and so this operations are interpreted as matrix multiplication and division by default. If you want to do a regular division or multiplication you use .* and ./. This is true also for power (^ and .^).

Related

Solving system of equations on MATLAB, when a constant exists in variable matrix?

How do I solve the following system of equations on MATLAB when one of the elements of the variable vector is a constant? Please do give the code if possible.
More generally, if the solution is to use symbolic math, how will I go about generating large number of variables, say 12 (rather than just two) even before solving them?
For example, create a number of symbolic variables using syms, and then make the system of equations like below.
syms a1 a2
A = [matrix]
x = [1;a1;a2];
y = [1;0;0];
eqs = A*x == y
sol = solve(eqs,[a1, a2])
sol.a1
sol.a2
In case you have a system with many variables, you could define all the symbols using syms, and solve it like above.
You could also perform a parameter optimization with fminsearch. First you have to define a cost function, in a separate function file, in this example called cost_fcn.m.
function J = cost_fcn(p)
% make sure p is a vector
p = reshape(p, [length(p) 1]);
% system of equations, can be linear or nonlinear
A = magic(12); % your system, I took some arbitrary matrix
sol = A*p;
% the goal of the system of equations to reach, can be zero, or some other
% vector
goal = zeros(12,1);
% calculate the error
error = goal - sol;
% Use a cost criterion, e.g. sum of squares
J = sum(error.^2);
end
This cost function will contain your system of equations, and goal solution. This can be any kind of system. The vector p will contain the parameters that are being estimated, which will be optimized, starting from some initial guess. To do the optimization, you will have to create a script:
% initial guess, can be zeros, or some other starting point
p0 = zeros(12,1);
% do the parameter optimization
p = fminsearch(#cost_fcn, p0);
In this case p0 is the initial guess, which you provide to fminsearch. Then the values of this initial guess will be incremented, until a minimum to the cost function is found. When the parameter optimization is finished, p will contain the parameters that will result in the lowest error for your system of equations. It is however possible that this is a local minimum, if there is no exact solution to the problem.
Your system is over-constrained, meaning you have more equations than unknown, so you can't solve it. What you can do is find a least square solution, using mldivide. First re-arrange your equations so that you have all the constant terms on the right side of the equal sign, then use mldivide:
>> A = [0.0297 -1.7796; 2.2749 0.0297; 0.0297 2.2749]
A =
0.029700 -1.779600
2.274900 0.029700
0.029700 2.274900
>> b = [1-2.2749; -0.0297; 1.7796]
b =
-1.274900
-0.029700
1.779600
>> A\b
ans =
-0.022191
0.757299

Understanding Non-homogeneous Poisson Process Matlab code

I have found the following Matlab code to simulate a Non-homogeneous Poisson Process
function x = nonhomopp(intens,T)
% example of generating a
% nonhomogeneousl poisson process on [0,T] with intensity function intens
x = 0:.1:T;
m = eval([intens 'x']);
m2 = max(m); % generate homogeneouos poisson process
u = rand(1,ceil(1.5*T*m2));
y = cumsum(-(1/m2)*log(u)); %points of homogeneous pp
y = y(y<T); n=length(y); % select those points less than T
m = eval([intens 'y']); % evaluates intensity function
y = y(rand(1,n)<m/m2); % filter out some points
hist(y,10)
% then run
% t = 7 + nonhomopp('100-10*',5)
I am new to Matlab and having trouble understanding how this works. I have read the Mathworks pages on all of these functions and am confused in four places:
1) Why is the function defined as x and then the intervals also called x? Like is this an abuse of notation?
2) How does the square brackets affect eval,
eval([intens 'x'])
and why is x in single quotations?
3) Why do they use cumsum instead of sum?
4) The given intensity function is \lambda (t) = 100 - 10*(t-7) with 7 \leq t \leq 12 How does t = 7 + nonhomopp('100-10*',5) represent this?
Sorry if this is so much, thank you!
To answer 2). That's a unnecessary complicated piece of code. To understand it, evaluate only the squared brackets and it's content. It results in the string 100-10*x which is then evaluated. Here is a version without eval, using an anonymous function instead. This is how it should have been implemented.
function x = nonhomopp(intens,T)
% example of generating a
% nonhomogeneousl poisson process on [0,T] with intensity function intens
x = 0:.1:T;
m = intens(x);
m2 = max(m); % generate homogeneouos poisson process
u = rand(1,ceil(1.5*T*m2));
y = cumsum(-(1/m2)*log(u)); %points of homogeneous pp
y = y(y<T); n=length(y); % select those points less than T
m = intens(y); % evaluates intensity function
y = y(rand(1,n)<m/m2); % filter out some points
hist(y,10)
Which can be called like this
t = 7 + honhomopp(#(x)(100-10*x),5)
the function is not defined as x: x is just the output variable. In Matlab functions are declared as function [output variable(s)] = <function name>(input variables). If the function has only one output, the square brackets can be omitted (like in your case). The brackets around the input arguments are, as instead, mandatory, no matter how many input arguments there are. It is also good practice to end the body of a function with end, just like you do with loops and if/else.
eval works with a string as input and the square brackets apprently are concatenating the string 'intens' with the string 'x'. x is in quotes because, again, eval works with input in string format even if it's referring to variables.
cumsum and sum act differently. sum returns a scalar that is the sum of all the elements of the array whereas cumsum returns another array which contains the cumulative sum. If our array is [1:5], sum([1:5]) will return 15 because it's 1+2+3+4+5. As instead cumsum([1:5]) will return [1 3 6 10 15], where every element of the output array is the sum of the previous elements (itself included) from the input array.
what the command t = 7 + nonhomopp('100-10*',5) returns is simply the value of time t and not the value of lambda, indeed by looking at t the minimum value is 7 and the maximum value is 12. The Poisson distribution itself is returned via the histogram.

Using Hindmarsh’s ODE solver LSODE in OCTAVE

I am learning OCTAVE, and I am trying to use LSODE ODE solver to integrate a version of FitzHugh–Nagumo model. My attempt looks like this:
time = linspace(0,200,1000);
u0 = rand(32,32);
v0 = rand(32,32);
vec_u0 = reshape(u0,[1,size(u0)(1)*size(u0)(2)]);
vec_v0 = reshape(v0,[1,size(v0)(1)*size(v0)(2)]);
vec_FHN0 = horzcat(vec_u0,vec_v0);
FHN = lsode("FHN_eq_vec", vec_FHN0, time);
FHN(end)
where all of the functions I have defined are in the repository I have set in GitHub - link. I have created a function that transform the two 2D fields of the FHN model into a row vector (as I understand from the examples here the LSODE integrator use row vector as input). I got this error message:
>> fhn_integrate_lsode
warning: non-integer range used as index
warning: called from
FHN_eq_vec at line 3 column 7
fhn_integrate_lsode at line 9 column 5
error: reshape: can't reshape 0x1 array to 1x1 array
error: called from
FHN_eq_vec at line 4 column 3
fhn_integrate_lsode at line 9 column 5
error: lsode: evaluation of user-supplied function failed
error: called from
fhn_integrate_lsode at line 9 column 5
error: lsode: inconsistent sizes for state and derivative vectors
error: called from
fhn_integrate_lsode at line 9 column 5
>>
Someone knows what could be the problem?
This has been answered at http://octave.1599824.n4.nabble.com/Using-Hindmarsh-s-ODE-solver-LSODE-in-OCTAVE-td4674210.html
However, looking quickly at your code, the system that you want to
solve is probably an ordinary differential equation stemming from a
pde space discretization, i.e.,
$dx(t)/dt = f(x,t) := -K x(t) + r(t)$
with K being a square matrix (Laplacian?!) and f a time-dependent
function of matching dimension. I expect that your system is stiff
(due to the negative Laplacian on the right-hand side) and that you
are happy with errors in the order of 10^(-4). Thus you should adapt
the options of lsode:
lsode_options("integration method","stiff");
lsode_options("absolute tolerance",1e-4);
lsode_options("relative tolerance",1e-4);
Then
T = 0:1e-2:1; % time vector
K = sprandsym(32,1)+eye(32); % symmetric stiffness matrix
x0 = rand(32,1); % initial values
r = #(t) rand(32,1)*sin(t); % excitation vector
f = #(x,t) (-K*x+r(t)); % right-hand-side function
x=lsode (f, x0, T); % get solution from lsode
You should exploit any knowledge on the Jacobian df/dx since this will
speed up computations. It's trivial in the case of linear ODE:
f = {#(x,t) -K*x+r(t), #(x,t) -K}; % right-hand-side function.
On the other hand, if the system has an additional mass matrix
$M dx(t)/dt = -K x(t) + r(t)$
things might become more complicated. You probably want to use another
time stepper. Only if M has full rank then you could do
f = #(x,t) ( M\(-K*x+r(t)) ); % right-hand-side function
which is typically not very efficient.
Bye Sebastian

Find values of constants in equation using MATLAB

I have equation F(f)=a*f^3+b*f+c. I have known vectors of the data, p, independent variable, 'f'. I need to find values of a, b, c.
What I tried:
function [ val ] = myfunc(par_fit,f,p)
% This gives me a,b,c
% p= af^3 +bf +c
val = norm(p - (par_fit(1)*(f.^3))+ (par_fit(2)*f) + (par_fit(3)));
end
my_par = fminsearch(#(par_fit) myfunc(par_fit,f,p),rand(1,3));
This gives me my_par = [1.9808 -2.2170 -24.8039], or a=1.9808, b=-2.2170, and c=-24.8039, but I require that b should be larger than 5, and c should be larger than zero.
I think your problem might be because your objective function is incorrect:
val = norm(p - (par_fit(1)*(f.^3))+ (par_fit(2)*f) + (par_fit(3)));
should probably be:
val = norm(p-(par_fit(1)*f.^3+par_fit(2)*f+par_fit(3)));
But you can constrain the values of variables when you do minimisation by using fmincon rather than fminsearch. By setting the lb input to [-Inf -Inf 0], the first two coefficients are allowed to be any real number, but the third coefficient must be greater than or equal to zero. For example: (I've also shown how to solve the problem (without the non-negativity constraint) using a matrix method)
% Sample data
f=(0:.1:1).';
p=2*f.^3+3*f+1+randn(size(f))
% Create Van der Monde matrix
M=[f.^3 f f.^0];
C=M\p; % Solve the matrix problem in a least squares sense if size(f)>size(F)
my_par=fmincon(#(c) norm(p-(c(1)*f.^3+c(2)*f+c(3))),rand(1,3),[],[],[],[],[-Inf 5 0],[])
C.'
plot(f,p,'o',f,M*C,f,my_par(1)*f.^3+my_par(2)*f+my_par(3))

need explanation about a matlab code snippet about moran process

I am new to Matlab. I was reading this code snippet, but in some parts (marked with asterisks) I don't understand what it means, so if anybody could help would be very much appreciated
function [A1nmb] = moran(initsize, popsize)
% MORAN generates a trajectory of a Moran type process
% which gives the number of genes of allelic type A1 in a population
% of haploid individuals that can exist in either type A1 or type A2.
% The population size is popsize and the initial number of type A1
% individuals os initsize.
% Inputs: initsize - initial number of A1 genes
% popsize - the total population size (preserved)
if (nargin==0)
initsize=10;
popsize=30;
end
A1nmb=zeros(1,popsize);
A1nmb(1)=initsize;
**lambda = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');
mu = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');**
x=initsize;
i=1;
while (x>1 & x<popsize+1)
if (lambda(x,popsize)/(lambda(x,popsize)+mu(x,popsize))>rand)
x=x+1;
A1nmb(i)=x;
else
x=x-1;
A1nmb(i)=x;
end;
i=i+1;
end;
nmbsteps=length(A1nmb);
***rate = lambda(A1nmb(1:nmbsteps-1),popsize) ...
+mu(A1nmb(1:nmbsteps-1),popsize);***
**jumptimes=cumsum(-log(rand(1,nmbsteps-1))./rate);**
jumptimes=[0 jumptimes];
stairs(jumptimes,A1nmb);
axis([0 jumptimes(nmbsteps) 0 popsize+1]);
The first line you marked
lambda = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');
creates something called an inline function. It is equivalent to defining a mathematical function. Example:
y = inline('x^2')
would allow you to do
>> y(2)
4
This immediately explains the second line you marked.
rate = lambda(A1nmb(1:nmbsteps-1),popsize) ...
+mu(A1nmb(1:nmbsteps-1),popsize);
will compute the value of the function lambda(x,N) at x = A1nmb(1:nmbsteps-1) and N = popsize.
I will say immediately here that you should take a look at anonymous functions, a different format used to accomplish the same as inline. Only, anonymous functions are generally better supported, and usually a lot faster than inline functions.
Then, for the final line,
jumptimes = cumsum(-log(rand(1,nmbsteps-1))./rate);
is a nested command. rand will create a matrix containing pseudorandom numbers, log is the natural logarithm ("ln"), and cumsum creates a new matrix, where all the elements in the new matrix are the cumulative sum of the elements in the input matrix.
You will find the commands doc and help very useful. Try typing
doc cumsum
or
help inline
on the Matlab command prompt. Try that again with the commands forming the previous statement.
As a general word of advice: spend an insane lot of time reading through the documentation. Really, for each new command you encounter, read about it and play with it in a sandbox until you feel you understand it. Matlab only becomes powerful if you know all its commands, and there are a lot to get to know.
It defines an inline function object. For example this
lambda = inline('(x-1).*(1-(x-1)./N)', 'x', 'N')
defines lambda as a function with 2 variables. When you call lambda(A,n) Matlab simply expands the function you define in the first string. Thus lambda(A,n) using the variables you provide in the function call. lambda(A,n) would will evaluate to:
(A-1).*(1-(A-1)./n)
it just expands the function using the parameters you supply. Take a look at this link for more specific details http://www.mathworks.co.uk/help/techdoc/ref/inline.html
The cumsum function just returns the cumulative sum of a matrix along a particular dimension. Say we call cumsum on a vector X, then the value at element i in the result is equal to the sum of elements in X from index 1 to i. For example X = [1 2 1 3] we would get
AA = cumsum(X);
we would have
AA = [1 3 5 8]
See this link for more details and examples http://www.mathworks.co.uk/help/techdoc/ref/cumsum.html