Passing in an function to solve integral equation with fsolve - matlab

I am trying to solve an integral equation of the form
Integrate[f(x)*g(x,w),dx]
Solve for w: ------------------------ = 0.5
Integrate[f(x),dx]
of which there are definite limits (numerical integration).
Searching around on this and mathworks website I found some code that does it using functions in functions. I have run into a few problems though:
The code currently is (simplified equations for testing):
function [bfound]=testingSolveIntegral
options = optimset('MaxFunEvals',50);
bfound = fsolve(#func2minimize,[1 2 3],options); %testing start points at 1,2,3
function output = func2minimize(w)
t0 = -1;
t1 = 1;
L = 0.5;
output = (L - (integral(#myFunc,t0,t1,'ArrayValued',true,'RelTol',1e-30,'AbsTol',1e-30)./integral(#myFunc2,t0,t1,'ArrayValued',true,'RelTol',1e-30,'AbsTol',1e-30)));
function f = myFunc(muu)
f = B.*muu.^2*(w.*muu.^2);
end
function f2 = myFunc2(muu)
f2 = B.*muu^2;
end
end
end
This works wonderfully, but what I would like to do is then solve these equations in a loop for different values of B, eg, B = 1:1:100. I have tried a few things inside this code but only get errors.
Do I need to call this function from an outside script which dictates the B loop?
I would also like to define my functions in this outside script eg something like:
func = #(muu) B.*muu.^2*(w.*muu.^2);
func2 = #(muu) B.*muu^2;
for B = 1:1:100
testingSolveIntegral(func,func2,B)
I have tried a few things but am getting lost in the torrent of functions flying around the place. Assistance on how to set up such a script would be greatly appreciated.
Thanks

The integral doc page tells you how to perfom this task (section "Integrate Parametrized Function").
First define functions f and g with as many arguments as you have parameters/variables. For example, define:
g = #(muu,w) muu.^2*(w.*muu.^2);
f = #(muu) muu.^2;
Then call integral with an anonymous function which fix the values of the parameters:
for w=1:100
q(w) = integral(#(x) g(x,w).*f(x),bmin, bmax)./integral(f,bmin, bmax);
end

Related

How to create a function that takes a matrix as an input?

I am new to MatLab.
Write a function that takes as input a matrix D ∈ R^(N×2), D_i = (x_i,y_i), and the period ω and returns a plot showing a fit of the data without noise.
I need help with creating the function that takes the input as a matrix and period ω. Here is what I have so far. Am I on the right track?
function F = fftfuntion(D, omega)
check = 0;
x = D(:,1);
y = D(;,2);
You are on track but there are 3 problems:
First: you are using p variable inside your function which is not defined there. If it is defined in your main code you have to insert it to this function by adding an input to your function as p and when the function is called you have to put p there. Your other solution is to set p as a global variable which is not recommended.
function F = fftfuntion(D, omega,p)
Second: you have said that you need omega as an input and you are changing it with omega = 2*pi which is not right.
Finally I don't see any output which I think that's because you are not still done with the function.
Good luck

MATLAB: Slow Read-in of constant variables in Script Function

In the latest MATLAB release, I am using the feature of local functions in the script to simplify and shorten the code.
Right now I have a simple script that does mathematical calculations, up to millions of iterations in a for loop. From the loop, I extracted the mathematical part as it is used in multiple independent loops. However, I have the problem with speed and constant variables that need to be in the function. If I write the code without the local function, it is fast, but in the case of using the function, it is 10x slower.
I think it is due to the repetitive read-in of variables in the function. If the read-in happens from a file, it takes forever. The best I have achieved is by using evalin function to call in variables from the base workspace. It works, but as I mentioned, it is 10x slower than without a separate local function.
How to overcome this?
The structure looks like this:
load('Data.mat'); r=1; %Reads variables L,n
for Lx = L1:Ld:L2
for x = x1:d:x2
Yx(r) = myF(x); r=r+1
end
end
%A few more different loops...
function y = myF(x)
L = evalin('base','L');
n = evalin('base','n');
...
a = (x-L)^2; b = sin(a)-n/2; ... y=b*a/L;
end
You will want to explicitly pass the variables as additional input arguments to myF so that you don't have to load them every time. This way you don't have to worry about calling evalin or loading them from the file every iteration through the loop.
load('Data.mat'); r=1; %Reads variables L,n
for Lx = L1:Ld:L2
for x = x1:d:x2
Yx(r) = myF(x, L, n); r=r+1
end
end
function y = myF(x, L, n)
a = (x-L)^2; b = sin(a)-n/2;
y=b*a/L;
end
If for some reason you can't modify myF, just turn the entire thing into a function and make myF a subfunction and it will therefore automatically have access to any variable within the parent function. In this case you'll also want to assign the output of load to a variable to prevent strange behavior and not have issues with adding a variable to a static workspace
function myfunction()
data = load('Data.mat');
L = data.L;
n = data.n;
for Lx = L1:Ld:L2
for x = x1:d:x2
Yx(r) = myF(x);
r=r+1
end
end
function y = myF(x)
a = (x-L)^2; b = sin(a)-n/2;
y=b*a/L;
end
end
A third alternative is to take a hard look at myF and consider whether you can vectorize the contents so that you don't actually have to continuously call it millions of times.
You could vectorize it by doing something like
[Lx, x] = ndgrid(L1:Ld:L2, x1:d:x2);
a = (x - L).^2;
b = sin(a) - (n / 2);
Yx = (b .* a) ./ L;

Matlab Defining A Function That Has Vector As An Input

I was given a simple exercise by my professor, which is to define a cerrtain function. Here is my function
function [a,b,c] = PHUN([x,y],[z,t,w])
a = x
b = ((y+z)^2)*t
c = z/w + x
However, matlab states that I am using invalid syntax in the first line. So, I figured, perhaps there is a particular way in which vector inputs are supposed to be typed. I have attempt several searches on defining functions with vector inputs (or arguments), but have not been successful. I was wondering if someone could possibly help me.
You can pass vectors as arguments in the same way you pass variables. Then access them in the function body appropriately. Your function could be re-written as follows:
function [a,b,c] = PHUN(X,Y)
a = X(1)
b = ((X(2)+Y(1))^2)*Y(2)
c = Y(1)/Y(3) + X(1)
Or if you want to keep the original variables:
function [a,b,c] = PHUN(X,Y)
Z = num2cell([X,Y]);
[x,y,z,t,w] = Z{:};
a = x
b = ((y+z)^2)*t
c = z/w + x

Why can't I pass a function handle to fsolve, but I can write an equivalent anonymous function in fsolve?

I find this somewhat odd. I am currently writing a simple function to solve a system of equations using fsolve. Here is what I have:
%Variable Declarations
I0 = 10e-12;
n = 1;
Vt = 0.0259;
R = 10e3;
Vs = 3;
%Function 1 (Some may recognize that this is the Shockley Diode Equation, if anyone cares...)
i1 = #(v1)(I0) * (exp((v1)/(n*Vt))-1);
%Function 2
i2 = #(v1) ((Vs-v1)/R);
%This is what I originally tried
h = #(v1) i1(v1)-i2(v1);
fsolve(h(v1), 1)
%After running this, I receive "Undefined function or variable 'v1.'"
% However, if I write
fsolve(#(v1)i1(v1)-i2(v1),1)
%The function works. With the result, I plugged that value into h(v1), and it produces the expected result (very close to 0)
That said, why doesn't matlab allow me to pass a function handle to fsolve?
You want to pass a function handle, which is h, not h(v1). h(v1) itself can't be evaluated because v1 is not defined.
Try fsolve(h, 1)

Passing argument to inner function Matlab

So I'm trying to write a function for a triple integral which depends ultimately on variable q which is a final limit of integration, and also a variable b which helps parameterize the function. However, this code isn't working and I'm not entirely sure what to do. I think it probably involves doing something to pass down the value of b to the nested functions, but I'm pretty new at matlab, any help is appreciated.
function [r] = test1(q,u)
b = u;
r = quad(#(k)Inner(k),-0.5.*(1-b)-b-1,q);
function [w] = Inner(k)
w = zeros(1);
for i = 1 : length(k);
w(i) = quad(#(n)InnerIntegral(n,b).*unifpdf(k(i)-n,-1,1),0,k(i)-1,k(i)+1);
end;
function [y] = InnerIntegral(n)
y = zeros(1);
for i = 1 : length(n);
y(i) = quad(#(m)unifpdf(n(i)-m, -b, b).*unifpdf(m,-0.5.*b,0.5.*b), n(i)-b,n(i)+b);
end;
end
end
end
Look at the little orange tick marks on the right side of the editor. In my copy, hovering over one says "Outer loop index 'i' is set inside a child function."
I don't know what the inputs or expected outputs of this function should be, but you should try to avoid confusing MATLAB. It has weird scoping rules. Use a different variable in the second nested function, perhaps j instead of i.