nlinfit Dimension Error - matlab

I am using nonlinearfit tool in matlab.
I keep getting the following error:
Error using nlinfit (line 210)
MODELFUN must be a function that returns a vector of fitted values the same size as Y (1-by-100). The model function you provided returned a result that was 1-by-2.
One common reason for a size mismatch is using matrix operators (, /, ^) in your function instead of the corresponding element-wise operators (., ./, .^).
I found this question very similar to mine, but still I get the same error. I have tried calculating myfun on the console while using a vector as an input, which gives me output of correct dimension. It will be ton of help if anybody can point out the mistake.
% Defining the function
myfun = #(t,b)exp(t.*b(1)+b(2));
[y_a] = arrayfun(myfun,x_a);
% Using nonlinear least square minimization
beta0 = [1 1];
nlinfit(x,y,myfun, beta0)
Thanks in advance...:)
Edit: Found this to be working.
g = fittype('exp(k*x + a)');
[fit1,gof,fitinfo] = fit(x',y',g,'StartPoint',[1 1]);

The function used in nlinfit takes the parameter vector as its first argument, then the independent data vector. You want,
myfun = #(b,t)exp(t.*b(1)+b(2));
Note that you could just use * rather than .* in this instance too.

Related

Error when plotting in Octave

In Octave 4.0.2 I have defined a function S as follows:
S = #(x) (Y(k)+((Y(k+1)-Y(k))/h(k)-(2*M(k)+M(k+1))*h(k)/6)*(x-X(k))+M(k)*(k-X(k))^2/2+(M(k+1)-M(k))*(x-X(k))^3/(6*h(k)))
When I call it to evaluate a number in the interval [X(k), X(k+1)] I get the result I expect, but when I try plotting it with the command:
fplot(S, [X(k), X(k+1)]); hold on;
I get the error "error: for A^b, A must be a square matrix. Use .^ for elementwise power."
What is going on?
Alright, I figured out that when passing a function to fplot it must be able to take a vector of inputs and return a vector of outputs.

not enough input arguments fminsearch

I'm trying to write a script in MATLAB that graphs a function in three dimensions using the mesh function and then finds the maximum of the surface. This is my code so far:
%% Aquifer, 3D maximum search
figure(2)
[X,Y] = meshgrid(-10:.5:10,-10:.5:10);
h = #(x,y)-(1./(1+(x-.25).^2+(y-.5).^2+x+x.*y));
mesh(h(X,Y)) %graph aquifer surface
aquamax = fminsearch(h,[-5;-5])
When I run the code I get this error:
Error using #(x,y)-(1./(1+(x-.25).^2+(y-.5).^2+x+x.*y))
Not enough input arguments.
Error in fminsearch (line 190)
fv(:,1) = funfcn(x,varargin{:});
I've read up on the fminsearch function but I'm not that familiar with it (still a bit of a noob at Matlab). Do I need to rework the code or is it just how I've input things into fminsearch?
Your h function requires 2 scalar inputs, but fminsearch only does one input, possibly a vector. Change h to h = #(x)-(1./(1+(x(1)-.25).^2+(x(2)-.5).^2+x(1)+x(1).*x(2))); and see if that works.

fminsearch multiple parameters matlab

I'm trying to use fminsearch with multiple parameters but I can't seem to even get it working with two. I've also tried using optimization tool in matlab but then I get:
Optimization running.
Error running optimization.
Not enough input arguments.
What i do:
fval = fminsearch(#g,[1 1])
The function g looks like this:
function r=g(x,y)
r=x.^3+3*x*y.^2+12*x*y;
end
but i get this:
Error using g (line 2)
Not enough input arguments.
Error in fminsearch (line 190)
fv(:,1) = funfcn(x,varargin{:});
Your function g takes two inputs, x and y, however you supply fminsearch one input, the vector [1 1]. You need to rewrite it so that fminsearch only needs a single vector as input, but then that vector is split into two numbers to input into g.
fminsearch(#(v) g(v(1),v(2)),[1 1])
This makes an anonymous function that takes a vector as input (v) and then uses the first element (v(1)) as the first input to g, and the second element as the second input.

Converting symbolic equation to fitness function which can be evaluated by genetic algorithm

I have a symbolic equation and wish to convert to a function which can be evaluated by genetic algorithm (ga). I have tried using the matlabFunction and convert the symbolic equation into a matlab file. However, this generated file can only be evaluated by fmincon or patternsearch algorithms and not genetic algorithm. I get this error using ga.
Caused by: Failure in initial user-supplied fitness function evaluation. GA cannot continue.
It seems like the matlabFunction does not generate the format required by ga, can anyone please advise what's the solution/workaround to this problem?
The code are as follow:
N = 24;
X = sym('x',[2*N 1]);
Y = X(1:N);
W = 3.2516e-6.*Y.^3 - 0.0010074.*Y.^2 + 0.390950.*Y+2.2353;
Z = P.*W;
totR = sum(Z);
totR = subs(totR,[P],[price]);
matlabFunction(totR,'vars',{X},'file','objFcn');
% Call to ga
x1 = ga(#objFcn, N*2, A, b, Aeq, beq)
Thanks!
From the documentation for ga:
The fitness function should accept a row vector of length nvars and return a scalar value.
Your objFcn is accepts a column vector and throws an error if a row vector is passed in. You can fix this (I think) by changing this line to:
X = sym('x',[1 2*N]);
If P is non-scalar then you may need to transpose it. Of course, without runnable code there could be all sorts of other things going on too. There are probably other places and ways that you could fix the issue.

Matrix dimension error while calling mldivide in MATLAB

I am getting this error while running my code:
Error using ==> mldivide Matrix dimensions must agree.
Here is my code :
%make the plots of phase and group velocity vs discreteness of the grid
c=1;
a=input('Please enter the ratio cdt/dx : ')
figure(1)
R=2:40;
plot(R,phase_vel(R,a)/c)
xlabel('R=l/dx')
ylabel('u_phase/c')
%figure(2)
%plot(group_vel(R,a),R,0,40)
%xlabel('R=l/dx')
%ylabel('u_group/c')
and here are my functions :
function phase_velocity = phase_vel(R,a)
%numerical phase velocity of the discrete wave
c=1;
phase_velocity=(2*pi*c)/(R*knum(R,a));
end
function group_velocity =group_vel(R,a )
%numerical group velocity of the discrete wave
c=1;
group_velocity=(a*sin(knum(R,a)))/(sin(2*pi*a/R))
end
function knumber = knum(R,a)
%This is the k wave number
knumber=acos((1/a)^2*(cos(2*pi*a/R)-1)+1);
end
How can I resolve this error?
EDIT: I used . operator in every equation and i changed the limits of R=4:40
If your goal is to apply your formulas to each individual value in the vector R then you should be performing all of your computations using the element-wise arithmetic operators .*, ./, and .^ instead of the matrix operators *, /, and ^.
Your error is probably occurring in the first call to your function knum, specifically when you try to compute 2*pi*a/R. Since 2*pi*a is a single scalar value, you get an error when trying to perform matrix right division / using the row vector R. The really weird thing is the error message:
??? Error using ==> mldivide
Matrix dimensions must agree.
which implies you are using the matrix left division operator \, which you clearly aren't. I tested this in MATLAB R2010b and I get the same incorrect function name appearing in my message. I think this may just be a typo in the error message, and I've dropped a note to the MATLAB folks to take a look at it and clear it up.
I don't have the Symbolic Math Toolbox, but your problem seems to be that you are using plot, a function which can deal with arrays of numbers, and feeding it the result of a symbolic calculation. Have a look at the Matlab Help, where the Topic Creating Plots of Symbolic Functions suggests using ezplot(). Alternatively you need to evaluate your symbolic expression for certain input values to create an array of numbers that plot can deal with - but you can't use double() for that since it wouldn't know what numbers to plug into your variables.