Receiving unknown errors when trying to use fsolve to find the solutions of a function - matlab

I have to plot the solution for masses between 4 and 8kg, which I wrote using the code below:
weight=linspace(4,8,100)
Then I use a for loop to find the solutions for the weights within this vector, while also declaring the variable a, and a guess of the time required:
for z=1:length(weight)
a=(weight./(1360*pi)).^(1/3)
tguess=14400
timeinseconds=fsolve(#(t)cookingtimes(t,a),tguess)
timeinhours=timeinseconds/(60*60)
end
The function that I mentioned previously is below:
function F=cookingtimes(t,a)
k=1:22;
alpha=0.7*10^(-7);
F(1)=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).*(pi.^2).*((alpha.*t))./(a.^2)))-57/80
end
Where F(1) represents the following equation 1, which will be equal to 57/80. Rather than adding until infinity, I chose the value of 22 as the equation converges to this value. r/a is equal to 0.464, which is why this is present within my function.
When running this code, I am given errors that I cant manage to solve.
Arrays have incompatible sizes for this operation.
Error in Homework1>cookingtimes (line 58)
F(1)=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).*(pi.^2).*.((alpha.*t))./(a.^2)))-57/80
Error in Homework1 (line 28)
timeinseconds=fsolve(#(t)cookingtimes(t,a),tguess)
Error in fsolve (line 264)
fuser = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
The arrays that I have produced are all of the same length, which is why I am very stuck on this issue.

You are trying to perform an operation on two arrays that have different sizes. In your case, the issue may be caused by the fact that you are defining the variable a as a vector inside the for loop, but using it in the function cookingtimes as a scalar. To fix this, you can modify your function to accept a vector of a values and return a corresponding vector of function values.
I modified the cookingtimes function to accept a vector of a values, and return a corresponding vector of function values.
function F=cookingtimes(t,a)
k=1:22;
alpha=0.7*10^(-7);
F=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).* (pi.^2).*((alpha.*t))./(a.^2)))-57/80;
end
In the for loop, You need to compute a for each weight value, and use a vector of a values in the call to fsolve. Also store the solutions in a vector timeinseconds instead of a scalar, as there are multiple solutions to be found.
for z=1:length(weight)
a=(weight(z)./(1360*pi)).^(1/3); % compute a for each weight value
tguess=14400;
timeinseconds(z)=fsolve(#(t)cookingtimes(t,a),tguess);
timeinhours=timeinseconds/(60*60);
end

Related

How to resolve this Out of memory. The likely cause is an infinite recursion within the program error

I am tagging my question and code along with output please into it tell where I did wrong.
Write a function
function p=r1p(a,n,x)
that computes and return p=P*x where P is a 2x2 projection matrix of rank 1
with column space consisting of the scalar multiples of a and
with null space consisting of the scalar multiples of n.
Notes:
The function must be named r1p
a is a nonzero column vector with two components.
n is a nonzero column vector with two components.
x is a nonzero column vector with two components.
My code:
function p = r1p(a,n,x)
% computes the action of P, the 2x2 projection matrix of rank 1 having
% a as an eigenvector with eigenvalue 1 and
% n as an eigenvector with eigenvalue
a=[1; 0.01]
n=[0.01; 1]
x=[1; 0]
p=r1p(a,n,x)
end
Error:
Out of memory. The likely cause is an infinite recursion within the program.
Error in r1p (line 8)
p=r1p(a,n,x)
from the reason that are described in the comment, the function just calls itself each time. The stack, which is a memory that holds details about all the chain of function calls, just fills up till it catch the whole allocated memory, and can't make more call since there is no memory to write the additional call.
It seems that you are missing the point of the recursion. On each stage, the input for the recursion should be changed, getting closer to a "basic" input that will be calculated directly. So this is a stage that is missing at your code - the recursive call for the function must be under a certain condition, and this condition should be fulfilled in some stage.
in addition, it seems that your function does not perform any calculation with your inputs.
see here a simple example:
myFactorial = factorial(5)
function output=factorial(input)
if (input<=0)
output=1;
else
output=input*factorial(input-1);
end
end
you can see that:
the internal call for factorial is under condition
the input is decreased so finally the input is 1 and the function is not called again.
there is an internal calculation, that implements what the programmer wanted.

How to use fminunc with summation in matlab?

I am trying to solve the following function with fminunc:
Σ((x(i)-1).^2) for i = 1 to 20
My code is below:
fun4 = #(x) sum((x(i)-1).^2, i, 1, 20)
[x,fval,exitflag,output]= fminunc(fun4,[1,1])
And, it gives the following error:
??? Error using ==> sym.sym>notimplemented at 2514
Function 'subsindex' is not implemented for MuPAD symbolic objects.
Could you help me, please?
You should check out the sum documentation for details about how to use it to sum over a vector.
In your case, if you have a vector x of at least 20 elements, you can get the subvector of "x(i) for i in the range 1 to 20" by x(1:20).
You can subtract scalars from a vector just by using the standard subtract sign, but to then square all of the elements individually you should use an "element-wise" operator (having a dot before the operator, like .^). As it happens, you were already doing this anyway.
The 2nd, 3rd and 4th arguments you were passing to sum are causing an error, because sum doesn't expect the arguments you are passing to it. For further details on the inputs it does expect see the linked docs.
All of this means your function can be simplified:
fun4 = #(x) sum((x(1:20)-1).^2);

MATLAB: Using FZERO on a function which has a vector output

I am working on my thesis and running in some programming problems in Matlab. I am trying to implement the ''golden Bisection Method'' to speed up my code. To this end, I've consulted the build in function FZERO.
So I am determining the difference between two vectors which are both (1x20).
Difference = Clmax_dist-cl_vec;
Clmax_dist comes from a semi-empirical method and cl_vec comes from the excecution of an external AVL.exe file.
Essentially, this difference depends only on one single variable AOA because the Clmax_dist vector is a constant. Hence, I am constantly feeding a new AOA value to the AVL.exe to obtain a new cl_vec and compare this again to the constant Clmax_dist.
I am iterating this until one of the element in the vector becomes either zero or negative. My loop stops and reveals the final AOA. This is a time consuming method and I wanted to use FZERO to speed this up.
However, the FZERO documentation reveals that it only works on function which has a scalar as input. Hence, my question is: How can I use FZERO with a function which has a vector as an output. Or do i need to do something totally different?
I've tried the following:
[Difference] = obj.DATCOMSPANLOADING(AOA);
fun=#obj.DATCOMSPANLOADING;
AOA_init = [1 20];
AOA_root = fzero(fun,AOA_init,'iter');
this gave me the following error:
Operands to the || and && operators must be convertible to logical scalar values.
Error in fzero (line 423)
while fb ~= 0 && a ~= b
Error in CleanCLmax/run (line 11)
AOA_root = fzero(fun,AOA_init,'iter');
Error in InitiatorController/moduleRunner (line 11)
ModuleHandle.run;
Error in InitiatorController/runModule (line 95)
obj.moduleRunner(ModuleHandle);
Error in RunSteps (line 7)
C.runModule('CleanCLmax');
The DATCOMSPANDLOADING function contains the following:
function [Difference] = DATCOMSPANLOADING(obj,AOA)
[Input]= obj.CLmaxInput; % Creates Input structure and airfoil list
obj.writeAirfoils(Input); % Creates airfoil coordinate files in AVL directory
[Clmax_dist,YClmax,Cla_mainsections] = obj.Clmax_spanwise(Input); % Creates spanwise section CLmax with ESDU method
[CLa] = obj.WingLiftCurveSlope(Input,Cla_mainsections); % Wing lift curve slope
[Yle_wing,cl_vec] = obj.AVLspanloading(Input,CLa,AOA); % Creates spanloading with AVL
Difference = Clmax_dist-cl_vec;
end
If I need to elaborate further, feel free to ask. And of course, Thank you very much.
fzero indeed only works on scalars. However, you can turn your criterion into a scalar: You are interested in AOA where any of the elements in the vector becomes zero, in which case you rewrite your objective function to return two output arguments: minDifference, which is min(Difference), and Difference. The first output, minDifference is the minimum of the difference, i.e. what fzero should try to optimize (from your question, I'm assuming all values start positive). The second output you'd use to inspect your difference vector in the end.

Simulink Matlab Function Block 'Size mismatch' Error

I am using a Matlab function block in a Simulink model. The Input is a 1x32 binary stream and the Output y is an integer between 0 and 15. I have 2 variables defined within this function called chip=zeros(17,32) and reconst_op=zeros(1,32). My Problem is that when I compare these two variables in an if condition as follows:
function y = De_Spreading_Mod(input)
if all(reconst_op==chip(1,:)) .. do something..
OR 2. if all(reconst_op(1,:)==chip(1,:))
Both the above conditions cause Matlab throw an error as follows:
for case 1, Size mismatch (size [:? x 32] ~= size [1 x 32]). Mismatched varying and fixed sizes indicate a probable run-time error. If this diagnostic is incorrect, use indexing to explicitly make the varying size fixed.
for case 2, MATLAB Function Interface Error: Simulation stopped due to out of bounds error. Runtime Error: Attempted to access 1 element of data reconst_chip_op whose runtime size is 0.
However, if I run the same Piece of code in a separate m file, it works as expected but only in the Simulink embedded matlab function block, it is an issue.
Any help would be appreciated

Matlab: nest fzero in fminsearch

I am trying to minimize with respect to a variable "y" a function that contains a parameter which must be calculated as a solution of an equality that contains "y" as well (say, y=-3; in my complete problem it is an equation with no analytic closed form solution, so I really need fzero).
Because of this, I include the fzero function in the argument of fminsearch:
fminsearch( #(y) 10*fzero(#(y) y+3, 0)) ;
I get the error:
Error using fminsearch (line 85)
The input to FMINSEARCH should be either a structure with
valid fields or consist of at least two arguments.
I obviously get the same error with:
f = fzero(#(y) y+3, 0);
fminsearch(#(y) 10*f);
Apparently the problem is that I cannot "nest" a fzero inside fminsearch.
Any idea about how to turn around this problem?
If you read the error message you got and look at the documentation of fminsearch you'll see that you need to call it with two input arguments. You call it with only one.
fminsearch( #(y) 10*fzero(#(x) x+3, 0), 0 )