How to plot this integral function in MATLAB? - matlab

Struggling to figure out how to plot this function in MATLAB.
Thanks, any help would be appreciated!

#Rotem 's approach is very good, yet I would love to add few words. Since you haven't mentioned anything about the domain, I suppose function can be defined also for negative numbers. In that case you can use the alternative as:
t = linspace(-10, 10);
func = arrayfun(#(t) integral(#(x) (10*x.*(343-(x).^3))/50421, 0, min(7,t)), t);
plot(t, func);
I have fixed the x axis between -10 and 10 with linspace, you can manually change that to get what you desire. But, note that function will get a fixed value when t is greater than 7, since integral has a bound such as min(t,7).

I really hope my answer is correct...
The integral of x is from 0 to t, when t goes from 0 to 7:
t = linspace(0, 7);
sigma = arrayfun(#(m) integral(#(x) 10*x.*(343 - x.^3)/50421, 0, m), t);
plot(t, sigma);
%Test using for loop:
% y = zeros(size(t));
%
% for i = 1:length(t);
% y(i) = integral(#(x) 10*x.*(343 - x.^3)/50421, 0, t(i));
% end
%
% figure;plot(t, y);

Related

Gradient descent Search implemented in matlab theta1 incorrect

I studied the Machine learning course taught by Prof. Andrew Ng. This is the link
I try to implement the 1st assignment of this course. Exercise 2: Linear Regression based upon Supervised learning problem
1.Implement gradient descent using a learning rate of alpha=0.07.Since Matlab/Octave and Octave index vectors starting from 1 rather than 0, you'll probably use theta(1) and theta(2) in Matlab/Octave to represent theta0 and theta1.
I write down a matlab code to solve this problem:
clc
clear
close all
x = load('ex2x.dat');
y = load('ex2y.dat');
figure % open a new figure window
plot(x, y, '*');
ylabel('Height in meters')
xlabel('Age in years')
m = length(y); % store the number of training examples
x = [ones(m, 1), x]; % Add a column of ones to x
theta = [0 0];
temp=0,temp2=0;
h=[];
alpha=0.07;n=2; %alpha=learning rate
for i=1:m
temp1=0;
for j=1:n
h(j)=theta(j)*x(i,j);
temp1=temp1+h(j);
end
temp=temp+(temp1-y(i));
temp2=temp2+((temp1-y(i))*(x(i,1)+x(i,2)));
end
theta(1)=theta(1)-(alpha*(1/m)*temp);
theta(2)=theta(2)-(alpha*(1/m)*temp2);
I get the answer :
>> theta
theta =
0.0745 0.4545
Here, 0.0745 is exact answer but 2nd one is not accurate.
Actual answer
theta =
0.0745 0.3800
The data set is provided in the link. Can any one help me to fix the problem?
You get wrong results because you write long unnecessary code that is easily prone to bugs, that is exactly why we have matlab:
clear
x = load('d:/ex2x.dat');
y = load('d:/ex2y.dat');
figure(1), clf, plot(x, y, '*'), xlabel('Age in years'), ylabel('Height in meters')
m = length(y); % store the number of training examples
x = [ones(m, 1), x]; % Add a column of ones to x
theta=[0,0]; alpha=0.07;
residuals = x*theta' - y ; %same as: sum(x.*theta,2)-y
theta = theta - alpha*mean(residuals.*x);
disp(theta)

plot some data such as pairs in matlab

I want to plot some data, but I can't.
It is assumed that we have 820 rows in 2 columns, representing the x and y coordinates.
My code is as follows:
load('MyMatFileName.mat');
[m , n]=size(inputs);
s = zeros(m,2);
for m=1:820
if inputs(m,end-1)<2 & inputs(m,end)<2
x = inputs(m,end-1)
y = inputs(m,end)
plot(x,y,'r','LineWidth',1.5)
hold on
end
end
I've edited your code and added comments to explain the changes you could make, but see below I've also re-written your code to be more like how it should be done:
load('MyMatFileName.mat'); % It's assumed "inputs" is in here
% You don't use the second size output, so use a tilde ~
[m, ~] = size(inputs);
%s = zeros(m,2); % You never use s...
% Use a different variable for the loop, as m is already the size variable
% I've assumed you wanted ii=1:m rather than m=1:820
figure
hold on % Use hold on and hold off around all of your plotting
for ii=1:m
if inputs(m,end-1)<2 && inputs(m,end)<2 % Use double ampersand for individual comparison
x = inputs(m,end-1)
y = inputs(m,end)
% Include the dot . to specify you want a point, not a line!
plot(x, y, 'r.','LineWidth',1.5)
end
end
hold off
A better way of doing this whole operation in Matlab would be to vectorise your code:
load('MyMatFileName.mat');
[m, ~] = size(inputs);
x = inputs(inputs(:,end-1) < 2 & inputs(:,end) < 2, end-1);
y = inputs(inputs(:,end-1) < 2 & inputs(:,end) < 2, end);
plot(x, y, 'r.', 'linewidth', 1.5);
Note that this will plot points, if you want to plot the line, use
plot(x, y, 'r', 'linewidth', 1.5); % or plot(x, y, 'r-', 'linewidth', 1.5);

Optim-nonlinear equation in matlab code

I updated the question to clarify it more. Here is a graph:
For the curve in the attached photo, I hope to draw the curve. I have its equation and it is after simplification will be like this one
% Eq-2
(b*Y* cos(v) + c - k*X*sin(v))^2 + ...
sqrt(k*X*(cos(v) + 1.0) + b*Y*sin(v))^2) - d = 0.0
Where:
v = atan((2.0*Y)/X) + c
and b, c, d and k are constants.
from the attached graph,
The curve is identified in two points:
p1 # (x=0)
p2 # (y=0)
I a new on coding so accept my apologize if my question is not clear.
Thanks
So, after your edit, it is a bit more clear what you want.
I insist that your equation needs work -- the original equation (before your edit) simplified to what I have below. The curve for that looks like your plot, except the X and Y intercepts are at different locations, and funky stuff happens near X = 0 because you have numerical problems with the tangent (you might want to reformulate the problem).
But, after checking your equation, the following code should be helpful:
function solve_for_F()
% graininess of alpha
N = 100;
% Find solutions for all alphae
X = zeros(1,N);
options = optimset('Display', 'off');
alpha = linspace(0, pi/2, N);
x0 = linspace(6, 0, N);
for ii = 1:numel(alpha)
X(ii) = fzero(#(x)F(x, alpha(ii)), x0(ii), options);
end
% Convert and make an X-Y plot
Y = X .* tan(alpha);
plot(X, Y,...
'linewidth', 2,...
'color', [1 0.65 0]);
end
function fval = F(X, alpha)
Y = X*tan(alpha);
% Please, SIMPLIFY in the future
A = 1247745517111813/562949953421312;
B = 4243112111277797/4503599627370496;
V = atan2(2*Y,X) + A;
eq2 = sqrt( (5/33*( Y*sin(V) + X/2*(cos(V) + 1) ))^2 + ...
(5/33*( Y*cos(V) - X/2* sin(V) ))^2 ) - B;
fval = eq2;
end
Results:
So, I was having fun with this (thanks for that)!
Different question, different answer.
The solution below first searches for the constants causing the X and Y intercepts you were looking for (p1 and p2). For those constants that best fit the problem, it makes a plot, taking into account numerical issues.
In fact, you don't need eq. 1, because that's true always for any curve -- it's just there to confuse you, and problematic to use.
So, here it is:
function C = solve_for_F()
% Points of interest
px = 6;
py = 4.2;
% Wrapper function; search for those constants
% causing the correct X,Y intercepts (at px, py)
G = #(C) abs(F( 0, px, C)) + ... % X intercept at px
abs(F(py, 0, C)); % Y intercept at py
% Initial estimate, based on your original equation
C0 = [5/33
1247745517111813/562949953421312
4243112111277797/4503599627370496
5/66];
% Minimize the error in G by optimizing those constants
C = fminsearch(G, C0);
% Plot the solutions
plot_XY(px, py, C);
end
function plot_XY(xmax,ymax, C)
% graininess of X
N = 100;
% Find solutions for all alphae
Y = zeros(1,N);
X = linspace(0, xmax, N);
y0 = linspace(ymax, 0, N);
options = optimset('Display', 'off',...,...
'TolX' , 1e-10);
% Solve the nonlinear equation for each X
for ii = 1:numel(X)
% Wrapper function for fzero()
fcn1 = #(y)F(y, X(ii), C);
% fzero() is probably the fastest and most intuitive
% solver for this problem
[Y(ii),~,flag] = fzero(fcn1, y0(ii), options);
% However, it uses an algorithm that easily diverges
% when the function slope is large. For those cases,
% solve with fminsearch()
if flag ~= 1
% In this case, the minimum of the absolute value
% is searched for (which should be zero)
fcn2 = #(y) abs(fcn1(y));
Y(ii) = fminsearch(fcn2, y0(ii), options);
end
end
% Now plot the X,Y solutions
plot(X, Y,...
'linewidth', 2,...
'color', [1 0.65 0]);
xlabel('X'), ylabel('Y')
axis([0 xmax+.1 0 ymax+.1])
end
function fval = F(Y, X, C)
% Unpack constants
b = C(1); d = C(3);
c = C(2); k = C(4);
% pre-work
V = atan2(2*Y, X) + c;
% Eq. 2
fval = sqrt( (b*Y*sin(V) + k*X*(cos(V) + 1))^2 + ...
(b*Y*cos(V) - k*X* sin(V) )^2 ) - d;
end

MATLAB for loop plotting with varying parameter

I want to plot this
f(x)=3*(1-x)+7*x+8.314*T((1-x)*(lnx)+x*(lnx))+20*x(1-x)
with T varying from 0 to 2000 with interval of 100{A total of 20 graphs all in the same}
Give a very basic code involving for loop and plot function.
PS : I am a beginer in MATLAB
Welcome to Matlab. :) Here's how we would do this without the loop:
% Define your function in terms of x and T
% Note that we use .* instead of * - this does a pairwise multiply
% instead of a matrix or vector multiply
f = #(x,T) 3*(1-x)+7*x+8.314*T.*((1-x).*log(x)+x.*log(x))+20*x.*(1-x);
% Set your domain
x = linspace(0, 10, 101);
T = (0:100:2000);
% Compute your function for all values of x and T
tmp = bsxfun(f, x, T');
% Plot your output, all at the same time
plot(x, tmp)
f=#(x,T) 3*(1-x)+7*x+8.314*T*((1-x).*log(x)+x.*log(x))+20*x.*(1-x);
T=0:100:2000;
x=linspace(0,10,100);
for i=1:length(T)
plot(x,f(x,T(i)));
hold on;
end

animate plot / trajectory in matlab / octave

I'm trying to animate this spiral using matlab / octave I want it to spiral up or down
t = 0:0.1:10*pi;
r = linspace (0, 1, numel (t));
z = linspace (0, 1, numel (t));
plot3 (r.*sin(t), r.*cos(t), z);
I tried using a for loop to animate it but that just gives me a cone shape see code and image below
clear all, clc,clf,tic
t = 0:0.1:10*pi;
r = linspace (0, 1, numel (t));
z = linspace (0, 1, numel (t));
for ii=1:length(r)
ii
plot3 (r.*sin(t(ii)), r.*cos(t(ii)), z);
hold on
%pause (.00001)
end
Image
You could also use the comet3() package, which animates the trajectory through the plot:
delay = 0.001 % seconds
figure
comet3(r.*sin(t), r.*cos(t), z, delay);
This animates a continuous trajectory which I prefer over a discrete sequence of *'s.
The one downside is that the version of comet and comet3 that shipped with Octave 3.6.4 are slow, regardless of the delay you use. But this can be overcome by using the following trick courtesy of andyras in this SO question:
% plot the first point to get started
h = plot3(x(1),y(1),z(1),"b");
axis([min(x), max(x), min(y), max(y), min(z), max(z)]);
% refresh the plot in a loop through the rest of the data
for k = 1:length(z);
set(h, 'XData', x(1:k));
set(h, 'YData', y(1:k));
set(h, 'ZData', z(1:k));
pause (0.001); % delay in seconds
% alternatively could provide a velocity function
% pause(sqrt(vx(k)^2+vy(k)^2+vz(k)^2));
endfor
Minor note: once you've modified the function, you'll need to force Octave to reload it as it won't do this by default. You can either restart, or better yet use clear comet and clear comet3. Then the next time those functions are called, their definitions will be refreshed.
The following appears to work in Octave 3.6.2
t = 0:0.1:10*pi;
r = linspace (0, 1, numel (t));
z = linspace (0, 1, numel (t));
figure
axis([-1 1 -1 1 0 1])
hold on
for ii=1:length(r)
plot3 (r(ii)*sin(t(ii)), r(ii)*cos(t(ii)), z(ii),'*');
pause (.001)
end
Certainly not the prettiest, but these are the first changes you need to make to your code for it to do something close to what you want.
t = 0:0.1:10*pi;
z = linspace (1, 0, numel (t));
for ii=1:length(t)
plot3 (z(ii)*sin(t(ii)),z(ii)*cos(t(ii)), z(ii));
hold on
pause (.00001)
end
This is not the trajectory solution, but here is a spinning tornado.
phi = linspace(0, 10*pi, 300);
r = linspace (0, 1, 300);
z = linspace (0, 1, 300);
s = 100; %speed of turning
for t = 0:0.01:10 %t is time
plot3 (r.*sin(phi+t*s), r.*cos(phi+t*s), z);
pause(0.01)
end