Function presents data wrong, Monte Carlo method - matlab

I am trying to write a program that does integration with monte carlo method. One of its features is to place dots on the graph with different colours, blue or red depending on the if statement. The if statement is put in a "for" loop and i dont know why but it seems like the first option is ignored after first iteration. The whole thing looks like this :
but it should look like this :
In addition i dont know why but it looks like the plot makes some additional empty space at the top
The whole code is not finished yet, its just a matter of a few lines but these dots are so annoying that I want to figure out whats wrong first. Heres the code.
function p=montecarlo(f, a, b, n, t)
%f is a function provided by user
%a and b is a range
%n is the amount of random points
%t is a t=a:01:b vector to draw a plot
upper=max(f(t));
lower=min(f(t));
x=a+(b-a).*(rand(n,1)) %generates vector of random numbers from a to b
y=lower+(upper-lower).*(rand(n,1)) %generates vector of ranom numbers from min to max
hold on
for i=1:n
if y(i)>=f(i)
plot(x(i),y(i),'bo')
else
plot(x(i),y(i),'ro')
end
plot(t,f(t),'k')
end
end
Arguments provided to the function : f= x.^2+3*x+5, a= -4 , b= 2, n= 1000 .

The problem is simple. The statement:
if y(i)>=f(i)
is wrong. What you want to do is compare the random value y(i) with the function value at the corresponding point x(i), so it should be:
if y(i)>=f(x(i))
plot(x(i),y(i),'bo')
else
plot(x(i),y(i),'ro')
end

Related

MATLAB Initial Objective Function Evaluation Error

I am trying to create a plot in MATLAB by iterating over values of a constant (A) with respect to a system of equations. My code is pasted below:
function F=Func1(X, A)
%X(1) is c
%X(2) is h
%X(3) is lambda
%A is technology (some constant)
%a is alpha
a=1;
F(1)=1/X(1)-X(3)
F(2)=X(3)*(X(1)-A*X(2)^a)
F(3)=-1/(24-X(2))-X(3)*A*a*X(2)^(a-1)
clear, clc
init_guess=[0,0,0]
for countA=1:0.01:10
result(countA,:)=[countA,fsolve(#Func1, init_guess)]
end
display('The Loop Has Ended')
display(result)
%plot(result(:,1),result(:,2))
The first set of code, I am defining the set of equations I am attempting to solve. In the second set of lines, I am trying to write a loop which iterates through the values of A that I want, [1,10] with an increment of 0.01. Right now, I am just trying to get my loop code to work, but I keep on getting this error:
"Failure in initial objective function evaluation. FSOLVE cannot continue."
I am not sure why this is the case. From what I understand, this is the result of my initial guess matrix not being the right size, but I believe it should be of size 3, as I am solving for three variables. Additionally, I'm fairly confident there's nothing wrong with how I'm referencing my Func1 code in my Loop code.
Any advice you all could provide would be sincerely appreciated. I've only been working on MATLAB for a few days, so if this is a rather trivial fix, pardon my ignorance. Thanks.
Couple of issues with your code:
1/X(1) in function Func1 is prone to the division by zero miscalculations. I would change it to 1/(X(1)+eps).
If countA is incrementing by 0.01, it cannot be used as an index for result. Perhaps introduce an index ind to increment.
I have included your constant A within the function to clarify what optimization variables are.
Here is the updated code. I don't know if the results are reasonable or not:
init_guess=[0,0,0];
ind = 1;
for countA=1:0.01:10
result(ind,:)=[countA, fsolve(#(X) Func1(X,countA), init_guess)];
ind = ind+1;
end
display('The Loop Has Ended')
display(result)
%plot(result(:,1),result(:,2))
function F=Func1(X,A)
%X(1) is c
%X(2) is h
%X(3) is lambda
%A is technology (some constant)
%a is alpha
a=1;
F(1)=1/(X(1)+eps)-X(3);
F(2)=X(3)*(X(1)-A*X(2)^a);
F(3)=-1/(24-X(2))-X(3)*A*a*X(2)^(a-1);
end

for loop over the first column of a matrix and mean

I have codes to solve some stochastic equations.
My function file
[S,T]=simByEuler(MDL, nPeriods,'DeltaTime',params.dt);
is running fine where S is a matrix its first column is theta and the second column is phi. S has 1001 rows. T is a vector of time of dimension 1001*1. Please ignore T. Focus on S which has 2 columns theta and phi,
i.e S=[theta, phi]. Dimension of S is 1001*2.
I want to write a for loop to generate 500 sample of the theta then take the mean of all of these 500. To start, the code I put in the question has random parameters. This code should be inside the for loop so that as the loop start again the code:
[S,T]=simByEuler(MDL, nPeriods,'DeltaTime',params.dt);
will generate random variable and run the for loop till end to generate new theta. What I am looking for is to have a block of these 500 theta (remember theta is a column). This block should be of size 1001*500. Then I want to take the mean of all columns in this block so the mean should be of size 1001*1.
My questions are:
1) How to write a for loop to generate this block of size 1001*500.
2) How to take the mean of all columns in the block so that the mean will be of size 1001*1.
I hope my questions are clear and I really appreciate any help.
Is this what you look for?
N = 500; % the size of a block
S = zeros(1001,2,N);
for k = 1:N
[S(:,:,k),T]=simByEuler(MDL, nPeriods,'DeltaTime',params.dt);
end
mean_theta = mean(squeeze(S(:,1,:)),2);

Finding local maxima for 3d matrix

I am trying to implement Hough transform in Matlab to find circles in a picture.
In the accumulator matrix, the global maximum is 105 at A(32,31,24). So I'm able to get this: max circle
The problem is, how can i find the local maxima to find the rest of the circles?
I wrote this to find A(i,j,k) which is bigger than the 26 adjacent points (26-Connected voxel neighborhood):
[i j k]=find(A~=0) ;
f=0;
for s=1:size(i)
if(i(s)~=100&&j(s)~=100&&k(s)~=141&&i(s)~=1&&j(s)~=1&&k(s)~=1)
if (A(i(s),j(s),k(s))>A(i(s)-1,j(s),k(s))&&A(i(s),j(s),k(s))>A(i(s)+1,j(s),k(s))&&A(i(s),j(s),k(s))>A(i(s),j(s)-1,k(s))&&A(i(s),j(s),k(s))>A(i(s),j(s)+1,k(s))&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)-1,k(s))&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)+1,k(s))&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)+1,k(s))&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)-1,k(s))&&A(i(s),j(s),k(s))>A(i(s),j(s),k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s),k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s),k(s)+1)&&A(i(s),j(s),k(s))>A(i(s),j(s)-1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s),j(s)+1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)-1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)+1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)+1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)-1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s),j(s),k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s),k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s),k(s)-1)&&A(i(s),j(s),k(s))>A(i(s),j(s)-1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s),j(s)+1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)-1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)+1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)+1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)-1,k(s)-1))
f=f+1
i(s)
j(s)
k(s)
end
end
end
Why i never got these correct i,j,k and f is always 0? I think i should at least find (32,31,24) and f=1?
Can anyone help me ?
Thank you so much!
The complete code is here:
im=imread('C:\Users\dell\Desktop\tp-complet\Hough\four.png');
sigma = 0.3;
gausFilter = fspecial('gaussian',[5 5],sigma);
sobelFilter=fspecial('sobel');
img=imfilter(im,gausFilter,'replicate');
ims=edge(img,'sobel');
rmax=size(im,1);
cmax=size(im,2);
radmax=round(sqrt(rmax^2+cmax^2));
for i=1:rmax
for j=1:cmax
for k=1:radmax
A(i,j,k)=0;
end
end
end
[r c]=find(ims==1);
length=size(r);
for k=1:length
for l=1:rmax
for m=1:cmax
if((l~=r(k))&&(m~=c(k)))
x=sqrt((l-r(k))^2+(m-c(k))^2);
x=round(x);
A(l,m,x)=A(l,m,x)+1;
end
end
end
end
[i j k]=find(A~=0) ;
f=0;
for s=1:size(i)
if(i(s)~=100&&j(s)~=100&&k(s)~=141&&i(s)~=1&&j(s)~=1&&k(s)~=1)
if (A(i(s),j(s),k(s))>A(i(s)-1,j(s),k(s))&&A(i(s),j(s),k(s))>A(i(s)+1,j(s),k(s))&&A(i(s),j(s),k(s))>A(i(s),j(s)-1,k(s))&&A(i(s),j(s),k(s))>A(i(s),j(s)+1,k(s))&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)-1,k(s))&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)+1,k(s))&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)+1,k(s))&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)-1,k(s))&&A(i(s),j(s),k(s))>A(i(s),j(s),k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s),k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s),k(s)+1)&&A(i(s),j(s),k(s))>A(i(s),j(s)-1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s),j(s)+1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)-1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)+1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)+1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)-1,k(s)+1)&&A(i(s),j(s),k(s))>A(i(s),j(s),k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s),k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s),k(s)-1)&&A(i(s),j(s),k(s))>A(i(s),j(s)-1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s),j(s)+1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)-1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)-1,j(s)+1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)+1,k(s)-1)&&A(i(s),j(s),k(s))>A(i(s)+1,j(s)-1,k(s)-1))
f=f+1
i(s)
j(s)
k(s)
end
end
end
I don't have the image processing toolbox, so cannot readily run your code. However, a quick review indicates to me that you're using the find function incorrectly. When provided with 3 outputs (as you have it), find doesn't return the 3D indices, but rather row, column, and a vector of the values. That means that k is just a giant vector of 1's, and so your for loop's if k(s)~=1 statement is never satisfied. You should do something like [i,j,k]=ind2sub(size(A),find(A~=0)) if you instead want the 3D indices.
Also, FYI, this:
for i=1:rmax
for j=1:cmax
for k=1:radmax
A(i,j,k)=0;
end
end
end
Can be replaced with A=zeros(rmax,cmax,radmax);.

How to create a vector of the results in a for loop

I have a problem with the following code. I want to store all the values I am creating in the for loop below so that I can make a plot of it. I have tried several things, but nothing works. Does anyone know a simple method to create a vector of the results and then plot them?
dx=0.1;
t=1;
e=1;
for x=-1:dx:1
lower_bound=-100;
upper_bound=x/(sqrt(4*t*e));
e=1;
u=(1/sqrt(pi))*quad(#integ,lower_bound,upper_bound);
plot(x,u)
hold on
end
hold off
I would like to use as much of this matlab code as possible.
dx=0.1;
t=1;
e=1;
xval=[-1:dx:1].';
upper_bound = zeros(numel(xval),1);
u = zeros(numel(xval),1);
for ii=1:numel(xval)
x = xval(ii)
lower_bound=-100;
upper_bound(ii,1)=x/(sqrt(4*t*e));
u(ii,1)=(1/sqrt(pi))*quad(#integ,lower_bound,upper_bound(ii));
end
figure;
plot(xval,u)
by adding the (ii) behind your statements it saves your variables in an array. I did not use that on your lower_bound since it is a constant.
Note that I first created an array xval and called that with integers in ii, since subscriptindices must be positive integers in MATLAB. I also initialised both upper_bound and u by creating a zero matrix before the loop executes. This is handy since extending an existing vector is very memory and time consuming in MATLAB and since you know how big they will get (same number of elements as xval) you might as well use that.
I also got the plot call outside the loop, to prevent you from plotting 21 blue lines in 1 plot.

matlab matrices and fold list

i have two problems in mathematica and want to do them in matlab:
measure := RandomReal[] - 0.5
m = 10000;
data = Table[measure, {m}];
fig1 = ListPlot[data, PlotStyle -> {PointSize[0.015]}]
Histogram[data]
matlab:
measure =# (m) rand(1,m)-0.5
m=10000;
for i=1:m
data(:,i)=measure(:,i);
end
figure(1)
plot(data,'b.','MarkerSize',0.015)
figure(2)
hist(data)
And it gives me :
??? The following error occurred
converting from function_handle to
double: Error using ==> double
If i do :
measure =rand()-0.5
m=10000;
data=rand(1,m)-0.5
then, i get the right results in plot1 but in plot 2 the y=axis is wrong.
Also, if i have this in mathematica :
steps[m_] := Table[2 RandomInteger[] - 1, {m}]
steps[20]
Walk1D[n_] := FoldList[Plus, 0, steps[n]]
LastPoint1D[n_] := Fold[Plus, 0, steps[n]]
ListPlot[Walk1D[10^4]]
I did this :
steps = # (m) 2*randint(1,m,2)-1;
steps(20)
Walk1D =# (n) cumsum(0:steps(n)) --> this is ok i think
LastPointold1D= # (n) cumsum(0:steps(n))
LastPoint1D= # (n) LastPointold1D(end)-->but here i now i must take the last "folding"
Walk1D(10)
LastPoint1D(10000)
plot(Walk1D(10000),'b')
and i get an empty matrix and no plot..
Since #Itamar essentially answered your first question, here is a comment on the second one. You did it almost right. You need to define
Walk1D = # (n) cumsum(steps(n));
since cumsum is a direct analog of FoldList[Plus,0,your-list]. Then, the plot in your code works fine. Also, notice that, either in your Mathematica or Matlab code, it is not necessary to define LastPoint1D separately - in both cases, it is the last point of your generated list (vector) steps.
EDIT:
Expanding a bit on LastPoint1D: my guess is that you want it to be a last point of the walk computed by Walk1D. Therefore, it would IMO make sense to just make it a function of a generated walk (vector), that returns its last point. For example:
lastPoint1D = #(walk) (walk(end));
Then, you use it as:
walk = Walk1D(10000);
lastPoint1D(walk)
HTH
You have a few errors/mistakes translating your code to Matlab:
If I am not wrong, the line data = Table[measure, {m}]; creates m copies of measure, which in your case will create a random vector of size (1,m). If that is true, in Matlab it would simply be data = measure(m);
The function you define gets a single argument m, therefor it makes no sense using a matrix notation (the :) when calling it.
Just as a side-note, if you insert data into a matrix inside a for loop, it will run much faster if you allocate the matrix in advance, otherwise Matlab will re-allocate memory to resize the matrix in each iteration. You do this by data = zeros(1,m);.
What do you mean by "in plot 2 the y=axis is wrong"? What do you expect it to be?
EDIT
Regarding your 2nd question, it would be easier to help you if you describe in words what you want to achieve, rather than trying to read your (error producing) code. One thing which is clearly wrong is using expression like 0:steps(n), since you use m:n with two scalars m and n to produce a vector, but steps(n) produces a vector, not a scalar. You probably get an empty matrix since the first value in the vector returned by steps(n) might be -1, and 0:-1 produces an empty vector.