plotting line between points in a loop goes wrong - matlab

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:

Related

Using Trapezium Rule on any function and show a graph

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--');

How to speed up the plotting of graphs using pause()?

I understand that when plotting an equation for x iterations that when you use a pause with a decimal number you can speed up the time it takes to go from one iteration to the next. My question is there a way to speed it up even more? Basically I am running a upwind 1D advection equation and my plot is doing pretty slow even when I put a pause of say 0.0001. Any advice on making the speed of this program increase for plotting or would I just need to let it run its course.
Here is the code I am using:
clear;
clc;
%Set initial values
xmin=0;
xmax=1;
N=101; %Amount of segments
dt= 0.0001; % Time step
t=0; % t initial
tmax=2; % Run this test until t=2
u=1; %Velocity
dx = (xmax - xmin)/100 %finding delta x from the given information
x =xmin-dx : dx : xmax+dx; %setting the x values that will be plugged in
h0= exp(-(x- 0.5).^2/0.01); %Initial gaussian profile for t=0
h = h0;
hp1=h0;
nsteps =tmax/dt; % total number of steps taken
for n=1 : nsteps
h(1)=h(end-2); %Periodic B.C
h(end)=h(2);
for i =2 : N+1
if u>0
hp1(i) = h(i) - u*dt/dx *( h(i)-h(i-1)); %Loop to solve the FOU
elseif u<0
hp1(i) = h(i) - u*dt/dx*(h(i+1)-h(i)); %downwind
end
end
t=t+dt; %Increase t after each iteration
h= hp1; %have the new hp1 equal to h for the next step
initial= exp(-(x- 0.5).^2/0.01); % The initial plot when t =0
%hold on
plot(x,initial,'*') %plot initial vs moving
plot(x,h,'o-')
pause(0.0001);
%hold off
figure(2)
plot(x,initial) %plot end value
end
Isn't this "speedup" due to pause() flushing the graphic event buffer like drawnow, but apparently doing it faster? So it is not the length of the pause doing any work (in fact, I don't think the resolution is in the millisecond range on many machines) but just the command itself.
The thing really slowing down your code is those for loops. You should try to change the code to calculate the segments in parallel instead.

Finding time spent by data outside a bin in MATLAB

I have the following graph:
x-axis represents time and both x and y axis data are discrete. I want to find the time spent by the graph during the time it exits the bin marked by yellow and red lines and when it comes back. The problem is that x axis data is discrete and and I want the duration x(t') - x(t).
Suppose the graph cuts yellow line at say n= 3.2 and goes outside the bin and then again cuts the yellow line at say n = 5.1, then I want the duration (5.1-3.2). SImilarly for the red line as well. Any idea on how can I do that?
The MATLAB code to generate the data set is:
mu =4;
x(1)=0.2; % x_{0}
nn=1:1001;
for n=1:1000
x(n+1) = mu*x(n)*(1-x(n));
end
figure;
plot(nn,x);
hold on;
plot([1 1010],[0.49 0.49]);
xlabel('n');
ylabel('x_{n}');
title('Plot of the equation: x_{n+1} = 4x_{n}(1-x_{n}) for x_{0} = 0.2 with
a bin of width 0.01 from x_{n} = 0.49 to x_{n+1}= 0.50');
hold on;
plot([1 1010],[0.50 0.50]);
I hope i interpreted this correctly when answering. So you're looking for values of n where they are x_n are 0.5 and 0.49. this will take two matrices and a while or for loop that will go for the 1000 iterations. Inside that put two if statements one for 0.5 and one for 0.49. Inside each one set a matrix to store the n value

How to generate numbers that follows normal distribution but w.r.t. time in Matlab

As time moves along x-axis, the output value (may be freq or prob) be shown accordingly i.e. as time moves the values should increase initially till mean and then decrease. I have prespecified mean mu=10 and standard deviation sigma=2.
Do you mean you want to plot a Gaussian function? I am not sure if you also wanted some sort of animation. If not, you can modify the code below to turn off modification.
clear; close all; clc;
% Set the mean and standard deviation
mu = 10;
sigma = 2;
% Time t
t = linspace(0,20,101);
% The equation for a normal distribution
f = 1/(sqrt(2*pi)*sigma)*exp( -(t-mu).^2/(2*sigma^2));
hold on;
xlim([0,20]);
ylim([0,0.25]);
axis manual;
for i=1:length(t)
plot( t(1:i), f(1:i), 'b-');
pause(0.1);
end
hold off;

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-')