Using Trapezium Rule on any function and show a graph - matlab

I have successfully managed to create a code in which I can estimate the area beneath the curve using the Trapezium rule. What I am struggling to do is plot the corresponding graph. I've used x^2 as the example and in the image I've attached a=-5, b=5 and n=3. And the original x^2 graph is not coming up but rather a merge between the blue and green lines. Can someone help fix this? Thank you.
Figure 1
% Trapezium Rule
f=#H; % Input Function
a=input('Enter lower limit a: ');
b=input('Enter upper limit b: ');
n=input('Enter the no. of interval: ');
h=(b-a)/n;
sum=0;
% Sum of f(x_1) to f(x_n+1)
for k=1:1:n+1
x(k)=a+k*h;
y(k)=f(x(k));
sum=sum+y(k);
end
hold on
plot(x, y,'bo-');
% drawing of the function
plot([x(1:end); x(1:end)], [zeros(1,length(y)); y(1:end)], 'r-');
% vertical lines from the points
plot([x(1:end-1); x(2:end)], [y(1:end-1) ; y(1: end)], 'g--');
% Meant to be forming a trapizium
hold off
answer = (h*0.5)*(sum);
% answer=h/2*(f(a)+f(b)+2*sum);
fprintf('\n The value of integration is %f',answer);
function y = H(x)
y = x.^2;
end

Your green line does not go from the same value to the same value! It foes from one to the next. You forgot that.
% the only reason you do -1 is so the last y can go to the end! The same as x
plot([x(1:end-1); x(2:end)], [y(1:end-1) ; y(2: end)], 'g--');

Related

How to choose a specific value from a loop to be plotted against a range of values?

I cannot think of the proper wording for this, but I am trying to have my code run a loop that will input a value of X into an initial condition variable. This variable is then inputted into the heat equation to be plotted. From the code I want to choose a value which is at X(i=51) and plot it as T(x,T1). As i said before I don't know the proper wording to search for a possible solution. Any advice would be great!
clear;
clc;
% initialize given variables
A= 0.25;
L= pi;
Nx=101; Nt=10^(-4);
dx=L/(Nx-1);
T1=zeros(1,Nx);
x=linspace(0, L, Nx); %x distance
%Initial condition
%T1 will be the "new" T value and To will be the old
T1= x.*(pi-x);
%For plotting, time starts at 0.
t=0;
for n=1:50
To=T1;
t=t+1;
for i=2:Nx-1
T1(i)=To(i)+Nt *A*((To(i+1)-2*To(i)+To(i-1))/(dx^2))+ sin(5*x(i));
end
%B.C given than # T(0,t) & T(L,t) = 0
T1(1)=0; T1(end)=0;
figure(1)
plot(x,T1); set(gca, 'ylim',[-110 110]);
ylabel('Temperature along the Rod');
xlabel('Location on the Rod of length Pi');
title(sprintf('Time = %f seconds', t));
pause(0.001);
end
The expected out put that I want to plot is plot(x(i=51),T1) which would show an image just like this. For this plot I ran my code and altered i to =50:51 to get the needed values for the heat equation. I am trying to have this be plotted in the code shown and not have to rewrite my code over and over to get different plots because I change values such as i or time ect...
You want to plot a consistent value of x, specifically x(51), for every n.
This can be done a couple of ways
First, as individual points with hold on:
for n = 1:50
% ... calculation ...
hold on
plot( x(51), T1(51), '.' );
hold off
end
You could update the plot, this will be quicker to compute and has the advantage of showing a line plot
x_51 = NaN( 50, 1 );
T1_51 = NaN( 50, 1 );
p = plot( [], [] );
for n = 1:50
% ... calculation ...
x_51(n) = x(51);
T1_51(n) = T1(51);
set( p, 'XData', x_51, 'YData', T1_51 );
end

ploting a function under condition with Matlab [duplicate]

This question already has an answer here:
Multiple colors in the same line
(1 answer)
Closed 4 years ago.
I am looking for a solution to this problem:
consider a function f (x) = 2x + 1, with x belonging to [0, 1000]. Draw the representative curve of f as a function of x, so that if ||f (x)|| <3 the representative curve of f is in red color and else represent the curve of f in blue color.
Help me because I am a new user of Matlab software
The code below should do the trick:
% Obtain an array with the desired values
y = myfunc(x);
% Get a list of indices to refer to values of y
% meeting your criteria (there are alternative ways
% to do it
indInAbs = find((abs(y)<3));
indOutAbs = find((abs(y)>=3));
% Create two arrays with y-values
% within the desired range
yInAbs = y(indInAbs);
xInAbs = x(indInAbs);
% Create two arrays with y-values
% outside the desired range
yOutAbs = y(indOutAbs);
xOutAbs = x(indOutAbs);
% Plot the values
figure(1);
hold on;
plot( xInAbs, yInAbs, 'r')
plot( xOutAbs, yOutAbs, 'b')
legend('in abs', 'out abs', 'location', 'best')
There are alternative ways to do it which could be more efficient and elegant. However, this is a quick and dirty solution.
Your threshold cannot be too low, otherwise it has not enough data to plot (if threshold=3) or cannot see the blue part. Here I use 500 such that you can see.
function plotSeparate
clc
close all
k=0
threshold=500
for x=1:0.5:1000
k=k+1
y=f(x)
if abs(y)<threshold
t(k,:)=[x,y];
else
s(k,:)=[x,y];
end
end
plot(s(:,1),s(:,2),'-r',t(:,1),t(:,2),'-b')
end
function y=f(x)
y=2*x+1;
end

Plot while changing different parameters matlab

I've written the following code for pricing options in matlab:
function call=CallBinomial(S,E,T,r,sigma)
S=100;
E=90;
T=2;
r=0.03;
sigma=0.2;
n=50;
dt=T/n;1
u=exp(sigma*sqrt(dt)+(r+0.5*sigma^2)*dt); d=1/u;
disf=exp(-r*dt);
p=0.5;
X=zeros(n+1,n+1);
for k=1:(n+1)
X(n+1,k)=max(S*u^(k-1)*d^(n-k+1)-E,0);
end
for m=n:-1:1
for k=1:m
X(m,k)=disf*( p*X(m+1,k+1) + (1-p)*X(m+1,k) );
end
end
call=X(1,1)
I want to plot a graph of the changing value of the call as I vary different parameters S, r, sigma but i'm unsure of how to do this.
Here is a simle example where you can change the parameters to plot inside a for loop:
for i = 1:.1:2
plot(i,i); % plot different things
axis([0 3 0 3]); % forces a constant size of window
pause(.2); % pauses before the next plot
end

plotting line between points in a loop goes wrong

I am currently trying to simulate a random walk. The idea is to choose a random number between 0 and 2*pi and let the random walker go in that direction. Here is what I tried to do to simulate such a random walk:
before=[0 0]; %start in (0,0)
while 1
x=rand;
x=x*2*pi; %// choose random angle
increment=[cos(x),sin(x)] %// increments using the sine and cosine function
now=before+increment;
plot(before, now)
hold on
before=now;
pause(1);
end
I expect this program to plot lines and each new line starts at the ending point of the previous line, but this does not happen. I have no clue why it is not working.
You got the syntax for plot wrong, which is plot(X,Y). Change the call to
plot([before(1), now(1)], [before(2), now(2)])
and your program should work as expected.
Here is an improved version that does all the calculation vectorized and gives you two choices of output. The first one displays all at once and is very fast. The second one takes a lot of time depending on the amount of samples.
pts = [0,0]; % starting point
N = 10000; % sample count
x = rand(N,1) * 2*pi; % random angle
% calculate increments and points
inc = [cos(x),sin(x)];
pts = [pts;cumsum(inc,1)];
% plot result at once
figure;
plot(pts(:,1),pts(:,2));
% plot results in time steps
figure; hold on;
for i = 1:size(pts,1)
plot(pts(i:i+1,1),pts(i:i+1,2))
pause(1)
end
Here is an example of the output:

How to plot phasors of signals?

I have 3 singals and I'm trying to plot their phasors and their sum. I need to plot them end to end to demonstrate phasor addition. That is, the first phasor must start from the origin. The second phasor must start from the end of the first phasor. The third phasor must start from the end of the second one. In this way, the end point of the third phasor is the resulting phasor (considering that it starts at the origin). Horizontal and vertical axes are the real and imaginary axes, respectively in range of [-30, 30].
I just started using matlab today and this is due the night. I tried using plot, plot2, plot3, compass, and several ways but with all of them i failed. Compass was the closest to success.
I have amplitude and phase values of each phasor.
So how can I accomplish this task? Can you help me to draw two of phasors?
Any help is appreciated.
Thank you!
Related Example: from http://fourier.eng.hmc.edu/e84/lectures/ch3/node2.html
[example by spektre]
The following example should get you started:
First, the three phasors are defined.
% Define three complex numbers by magnitude and phase
ph1 = 20*exp(1i*0.25*pi);
ph2 = 10*exp(1i*0.7*pi);
ph3 = 5*exp(1i*1.2*pi);
Then, using cumsum, a vector containing ph1, ph1+ph2, ph1+ph2+ph3 is calculated.
% Step-wise vector sum
vecs = cumsum([ph1; ph2; ph3]);
vecs = [0; vecs]; % add origin as starting point
The complex numbers are plotted by real and imaginary part.
% Plot
figure;
plot(real(vecs), imag(vecs), '-+');
xlim([-30 30]);
ylim([-30 30]);
xlabel('real part');
ylabel('imaginary part');
grid on;
This produces the following figure:
figure(1); hold on;
ang = [0.1 0.2 0.7] ; % Angles in rad
r = [1 2 4] ; % Vector of radius
start = [0 0]
for i=1:numel(r)
plot([start(1) start(1)+r(i)*cos(ang(i))],[start(2) start(2)+r(i)*sin(ang(i))],'b-+')
start=start+[r(i)*cos(ang(i)) r(i)*sin(ang(i))]
end
plot([0 start(1)],[0 start(2)],'r-')