Differentiation consistency in matlab - matlab

I'm trying to write a program in matlab that checks how consistent the definition of the derivative becomes:
(f(x+h)-f(x))/h ~= f'(x)
when h is small enough. Thus far i have this:
function [errList] = diffConsistency(f,df,x,iMax,h0)
h=h0;
for i=1:iMax
leftSide = (f(x+h) - f(x)) / h;
rightSide = df(x);
errList = abs(leftSide - rightSide);
h = h*10^(-1);
end
I then use f=#(x)sin(x) and df=#(x)cosx, I'm new to using function handles so this might be wrong completely. iMax is set to 10 and h0 = 1, x=rand(10)
Could anyone check if this is even remotely correct. Especially the use of the function handles inside the diffConsistency function and use of the rand.
Should i define x differently, leftside rightside are correct? etc
Any feedback would help.
Thanks in advance

You use some specific data that obscures the result. You input 10x10 random numbers, and output a 10x10 matrix of errors, but this is only for the last i, as you overwrite errList every iteration!
change the function to:
function [errList] = diffConsistency(f,df,x,iMax,h0)
h=h0;
for i=1:iMax
leftSide = (f(x+h) - f(x)) / h;
rightSide = df(x);
errList(i) = abs(leftSide - rightSide);
h = h*10^(-1);
end
and if you call it as :
err=diffConsistency(#sin,#cos,rand,10,1)
and plot(err), you can clearly see how the error gets reduced each smaller h.

Related

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;

What is wrong with my Simpson algorithm?

I was trying to write an algorithm to approximate integrals with Simpson's method. When I try to plot it in a loglog plot, however, I don't get the correct order of accuracy which is O(h^4) (I get O(n)). I can't find any errors though. This is my code:
%Reference solution with Simpson's method (the reference solution works well)
yk = 0;
yj = 0;
href = 0.0001;
mref = (b-a)/href;
for k=2:2:mref-1
yk=yk+y(k*href+a);
end
for j=1:2:mref
yj=yj+y(href*j+a);
end
Iref=(href/3)*(y(a)+y(b)+2*yk+4*yj);
%Simpson's method
iter = 1;
Ehmatrix = 0;
for n = 0:nmax
h = b/(2^n+1);
x = a:h:b;
xodd = x(2:2:end-1);
xeven = x(3:2:end);
yodd = y(xodd);
yeven = y(xeven);
Isimp = (h/3)*(y(x(1))+4*sum(yodd)+2*sum(yeven)+y(b));
E = abs(Isimp-Iref);
Ehmatrix([iter],1) = [E];
Ehmatrix([iter],2) = [h];
iter = iter + 1;
end
figure
loglog(Ehmatrix(:,2),Ehmatrix(:,1))
a and b are the integration limits and y is the integrand that we want to approximate.
Djamillah - your code looks fine though the initialization of h is probably valid only for the case where a==0, so you may want to change this line of code to
h = (b-a)/(2^n+1);
I wonder if x = a:h:b; will always be valid - sometimes b may be included in the list, and sometimes it might not be, depending upon h. You may want to reconsider and use linspace instead
x = linspace(a,b,2^n+1);
which will guarantee that x has 2^n+1 points distributed evenly in the interval [a,b]. h could then be initialized as
h = x(2)-x(1);
Also, when determining the even and odd indices, we need to ignore the last element of x for both even and odd. So instead of
xodd = x(2:2:end-1);
xeven = x(3:2:end);
do
xodd = x(2:2:end-1);
xeven = x(3:2:end-1);
Finally, rather than using a vector y (how is this set?) I might just use the function handle to the function that I'm integrating instead and replace the calculation above as
Isimp = delta/3*(func(x(1)) + 4*sum(func(xodd)) + 2*sum(func(xeven)) + ...
func(x(end)));
Other than these tiny things (which are probably negligible), there is nothing in your algorithm to indicate a problem. It produced similar results to a version that I have.
As for the order of convergence, should it be O(n^4) or O(h^4)?
Taking into account Geoff's suggestions, and making a few other changes, it all works as expected.
%Reference solution with Simpson's method (the reference solution works well)
a=0;
b=1;
y=#(x) cos(x);
nmax=10;
%Simpson's method
Ehmatrix = [];
for n = 0:nmax
x = linspace(a,b,2^n+1);
h = x(2)-x(1);
xodd = x(2:2:end-1);
xeven = x(3:2:end-1);
yodd = y(xodd);
yeven = y(xeven);
Isimp = (h/3)*(y(x(1))+4*sum(yodd)+2*sum(yeven)+y(b));
E = abs(Isimp-integral(y,0,1));
Ehmatrix(n+1,:) = [E h];
end
loglog(Ehmatrix(:,2),Ehmatrix(:,1))
P=polyfit(log(Ehmatrix(:,2)),log(Ehmatrix(:,1)),1);
OrderofAccuracy=P(1)
You were getting O(h) accuracy because xeven=x(3:2:end) was wrong. Replacing it by xeven=x(3:e:end-1) fixes the code, and thus the accuracy.

How to pad cell-arrays in Matlab

Does someone know how to pad cell-arrays? For regular (multi-dimensional) arrays, I can use the function
A = padarray(A,dim,value)
However it won't accept cells...
Been searching but I can't find anything in the docs or google, thought I'd ask before trying to reprogram padarray() to accept cells... if someone knows how to do this, it would be much appreciated.
You can always use cellfun to apply a function to each cell in a cell array:
padize = 2;
A = cellfun( #(x) padarray(x,padsize), A ,'uni', 0);
I'm pretty sure regular Matlab has nothing for cell arrays just like it has nothing for numeric ones (padarray belongs to the Image Processing Toolbox). How difficult it is depends on how generic you need it - the basic symmetric empty-padded fixed-number-of-dimensions case is trivial:
function y = padcell2d(x, r)
y = cell(size(x) + r.*2);
y(r+1:end-r, r+1:end-r) = x;
end
Add complexity as required.
Since it was fun thinking of the simplest way to handle arbitrary dimensions, here's a really hacky way of n-dimensional symmetric empty padding without loops (tested on Octave):
function x = padcell(x, r)
if any(r>0) && ~any(r<0)
if isscalar(r) % otherwise, assume it's a value-per-dimension vector
r = repmat(r, 1, ndims(x));
end
sz = num2cell(size(x) + 2*r);
x{sz{:}} = []; % hooray for comma-separated lists!
x = circshift(x, r);
end
end

Function Definition Clarification in Matlab

I wrote some code that works just fine to evaluate theta on its own with some test input. However, I would like to take this code and turn it into a function that I can call within another matlab file. I keep getting the error message, "Function definitions are not permitted in this context."
I want to be able to define four vectors in another matlab file and call SP1 to evaluate theta for those inputs. I'm not sure where I'm going wrong, though. Please help!
Thanks so much.
clc
clear all
function theta = SP1(p,q1,w1,r)
% INPUT:
%function theta = SP1(p,q1,w1,r)
% p = [5; -7; 12];
% q1 = [17.3037; -3.1128; 2.48175];
% w1 = [1/sqrt(8); sqrt(3/8); 1/sqrt(2)];
% r = [1; 2; -3];
% Define vectors u and v as well as u' and v'.
u = p - r;
v = q1 - r;
w1_t = transpose(w1);
u_prime = u - w1 * w1_t * u;
v_prime = v - w1 * w1_t * v;
% Calculate theta if conditions are met for a solution to exist.
if (abs(norm(u_prime)-norm(v_prime))<0.01) & (abs((w1_t * u)-(w1_t * v))<0.01)
X = w1_t*cross(u_prime,v_prime);
Y = dot(u_prime,v_prime);
theta = atan2(X,Y)
else if (norm(u_prime) == 0 | norm(v_prime) == 0)
disp('Infinite Number of Solutions')
else
disp('Conditions not satisfied to find a solution')
end
end
I think you can just remove the top two lines,
clc
clear all
and save the rest of the code starting with function as SP1.m file.
Then you should be able to call this function as SP1 from other m files.
I think you're confused about how functions work. The first line of a function definition defines how many inputs and outputs MATLAB expects:
function theta = SP1(p,q1,w1,r)
This means that calling a function SP1 will require you to give four inputs, and will return one output. It doesn't mean that:
Your inputs need to be named p, q1 and so on
Your output will be called theta automatically
The function will automatically take in the input variables p, q1, etc if they exist in the workspace.
It also doesn't do any checking on the inputs; so if you require that inputs be of a certain type, size, etc. you need to write your own error checking at the start of the file. You might intend that those inputs be 3x1 vectors, but there's nothing in the function to tell MATLAB that. So, SP1(1,2,3,4) will work, to some extent - it will take those inputs and try to run them through the function, and if they don't cause an error it will give you an output. The output might be wrong, but the computer doesn't know that.
Once you have a function you can call it multiple ways from the command line or from within other functions or scripts. As previously mentioned you don't have to stick to the naming of variables within the function, as long as input variables exist when the function is called MATLAB will accept them:
theta = SP1(p8,q27,w35,not_r);
myoutput = SP1(any,variable,I,like);
I don't necessarily have to give an output (but then the first output will be routed to ans)
SP1(this,will,also,work);
If I have some variables stored in a *.mat file (the case you seem to be asking about), I can do it like this:
load('mydata.mat'); %this file contains stored variables p, q1, w1 and r
theta = SP1(p,q1,w1,r);

How can I plot data to a “best fit” cos² graph in Matlab?

I’m currently a Physics student and for several weeks have been compiling data related to ‘Quantum Entanglement’. I’ve now got to a point where I have to plot my data (which should resemble a cos² graph - and does) to a sort of “best fit” cos² graph. The lab script says the following:
A more precise determination of the visibility V (this is basically how 'clean' the data is) follows from the best fit to the measured data using the function:
f(b) = A/2[1-Vsin(b-b(center)/P)]
Granted this probably doesn’t mean much out of context, but essentially A is the amplitude, b is an angle and P is the periodicity. Hence this is also a “wave” like the experimental data I have found.
From this I understand, as previously mentioned, I am making a “best fit” curve. However, I have been told that this isn’t possible with Excel and that the best approach is Matlab.
I know intermediate JavaScript but do not know Matlab and was hoping for some direction.
Is there a tutorial I can read for this? Is it possible for someone to go through it with me? I really have no idea what it entails, so any feed back would be greatly appreciated.
Thanks a lot!
Initial steps
I guess we should begin by getting a representation in Matlab of the function that you're trying to model. A direct translation of your formula looks like this:
function y = targetfunction(A,V,P,bc,b)
y = (A/2) * (1 - V * sin((b-bc) / P));
end
Getting hold of the data
My next step is going to be to generate some data to work with (you'll use your own data, naturally). So here's a function that generates some noisy data. Notice that I've supplied some values for the parameters.
function [y b] = generateData(npoints,noise)
A = 2;
V = 1;
P = 0.7;
bc = 0;
b = 2 * pi * rand(npoints,1);
y = targetfunction(A,V,P,bc,b) + noise * randn(npoints,1);
end
The function rand generates random points on the interval [0,1], and I multiplied those by 2*pi to get points randomly on the interval [0, 2*pi]. I then applied the target function at those points, and added a bit of noise (the function randn generates normally distributed random variables).
Fitting parameters
The most complicated function is the one that fits a model to your data. For this I use the function fminunc, which does unconstrained minimization. The routine looks like this:
function [A V P bc] = bestfit(y,b)
x0(1) = 1; %# A
x0(2) = 1; %# V
x0(3) = 0.5; %# P
x0(4) = 0; %# bc
f = #(x) norm(y - targetfunction(x(1),x(2),x(3),x(4),b));
x = fminunc(f,x0);
A = x(1);
V = x(2);
P = x(3);
bc = x(4);
end
Let's go through line by line. First, I define the function f that I want to minimize. This isn't too hard. To minimize a function in Matlab, it needs to take a single vector as a parameter. Therefore we have to pack our four parameters into a vector, which I do in the first four lines. I used values that are close, but not the same, as the ones that I used to generate the data.
Then I define the function I want to minimize. It takes a single argument x, which it unpacks and feeds to the targetfunction, along with the points b in our dataset. Hopefully these are close to y. We measure how far they are from y by subtracting from y and applying the function norm, which squares every component, adds them up and takes the square root (i.e. it computes the root mean square error).
Then I call fminunc with our function to be minimized, and the initial guess for the parameters. This uses an internal routine to find the closest match for each of the parameters, and returns them in the vector x.
Finally, I unpack the parameters from the vector x.
Putting it all together
We now have all the components we need, so we just want one final function to tie them together. Here it is:
function master
%# Generate some data (you should read in your own data here)
[f b] = generateData(1000,1);
%# Find the best fitting parameters
[A V P bc] = bestfit(f,b);
%# Print them to the screen
fprintf('A = %f\n',A)
fprintf('V = %f\n',V)
fprintf('P = %f\n',P)
fprintf('bc = %f\n',bc)
%# Make plots of the data and the function we have fitted
plot(b,f,'.');
hold on
plot(sort(b),targetfunction(A,V,P,bc,sort(b)),'r','LineWidth',2)
end
If I run this function, I see this being printed to the screen:
>> master
Local minimum found.
Optimization completed because the size of the gradient is less than
the default value of the function tolerance.
A = 1.991727
V = 0.979819
P = 0.695265
bc = 0.067431
And the following plot appears:
That fit looks good enough to me. Let me know if you have any questions about anything I've done here.
I am a bit surprised as you mention f(a) and your function does not contain an a, but in general, suppose you want to plot f(x) = cos(x)^2
First determine for which values of x you want to make a plot, for example
xmin = 0;
stepsize = 1/100;
xmax = 6.5;
x = xmin:stepsize:xmax;
y = cos(x).^2;
plot(x,y)
However, note that this approach works just as well in excel, you just have to do some work to get your x values and function in the right cells.