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-')
Related
I need ideas to resize my axes to have a much more airy graph to better visualize and calculate the gain between the different curves.
I used the code : axis([0 6 1e-3 1e0]) or xlim([0 6]); ylim([1e-3 1e0])
I would like to have for example my curve with: xlim([0:0.2:6]) (just the idea, otherwise it's wrong on matlab).
Thank you!
If I understand what you want, you need more XTicks in the x limits mentioned. After you plot just:
set(gca,'XTick',0:0.2:6)
another way is to write:
h=plot(.... whatever you plot...
h.XTick=0:0.2:6
Logarithmic Plot:
To create the axes the function xticks() and yticks() can be used to set the intervals, start and endpoints. xticks() and yticks() essentially take vectors that define all the ticks on the scales/axes. Just in case you'd like to also edit the interval along the y-axis. This vector can be created by raising each element in the vector (-3,1:0) to be an exponent with a base of 10. Finally, setting gca (the current axis) to logarithmic will allow the vertical spacing between the ticks to be evenly distributed.
axis([0 6 1e-3 1e0]);
Start = 0; Interval = 0.2; End = 6;
X_Vector = (Start: Interval: End);
xticks(X_Vector);
Y_Vector = 10.^(-3: 1: 0);
yticks(Y_Vector);
set(gca, 'YScale', 'log');
title("Logarithmic Plot");
grid;
Ran using MATLAB R2019b
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:
I was wondering if you could advise me how I can connect several points together exactly one after each other.
Assume:
data =
x y
------------------
591.2990 532.5188
597.8405 558.6672
600.0210 542.3244
606.5624 566.2938
612.0136 546.6825
616.3746 570.6519
617.4648 580.4575
619.6453 600.0688
629.4575 557.5777
630.5477 584.8156
630.5477 618.5906
639.2696 604.4269
643.6306 638.2019
646.9013 620.7697
652.3525 601.1584
"data" is coordinate of points.
Now, I would like to connect(plot) first point(1st array) to second point, second point to third point and so on.
Please mind that plot(data(:,1),data(:,2)) will give me the same result. However, I am looking for a loop which connect (plot) each pair of point per each loop.
For example:
data1=data;
figure
scatter(X,Y,'.')
hold on
for i=1:size(data,1)
[Liaa,Locbb] = ismember(data(i,:),data1,'rows');
data1(Locbb,:)=[];
[n,d] = knnsearch(data1,data(i,:),'k',1);
x=[data(i,1) data1(n,1)];
y=[data(i,2) data1(n,2)];
plot(x,y);
end
hold off
Although, the proposed loop looks fine, I want a kind of plot which each point connect to maximum 2 other points (as I said like plot(x,y))
Any help would be greatly appreciated!
Thanks for all of your helps, finally a solution is found:
n=1;
pt1=[data(n,1), data(n,2)];
figure
scatter(data(:,1),data(:,2))
hold on
for i=1:size(data,1)
if isempty(pt1)~=1
[Liaa,Locbb] = ismember(pt1(:)',data,'rows');
if Locbb~=0
data(Locbb,:)=[];
[n,d] = knnsearch(data,pt1(:)','k',1);
x=[pt1(1,1) data(n,1)];
y=[pt1(1,2) data(n,2)];
pt1=[data(n,1), data(n,2)];
plot(x,y);
end
end
end
hold off
BTW it is possible to delete the last longest line as it is not related to the question, if someone need it please let me know.
You don't need to use a loop at all. You can use interp1. Specify your x and y data points as control points. After, you can specify a finer set of points from the first x value to the last x value. You can specify a linear spline as this is what you want to accomplish if the behaviour you want is the same as plot. Assuming that data is a 2D matrix as you have shown above, without further ado:
%// Get the minimum and maximum x-values
xMin = min(data(:,1));
xMax = max(data(:,1));
N = 3000; % // Specify total number of points
%// Create an array of N points that linearly span from xMin to xMax
%// Make N larger for finer resolution
xPoints = linspace(xMin, xMax, N);
%//Use the data matrix as control points, then xPoints are the values
%//along the x-axis that will help us draw our lines. yPoints will be
%//the output on the y-axis
yPoints = interp1(data(:,1), data(:,2), xPoints, 'linear');
%// Plot the control points as well as the interpolated points
plot(data(:,1), data(:,2), 'rx', 'MarkerSize', 12);
hold on;
plot(xPoints, yPoints, 'b.');
Warning: You have two x values that map to 630.5477 but produce different y values. If you use interp1, this will give you an error, which is why I had to slightly perturb one of the values by a small amount to get this to work. This should hopefully not be the case when you start using your own data. This is the plot I get:
You'll see that there is a huge gap between those two points I talked about. This is the only limitation to interp1 as it assumes that the x values are strictly monotonically increasing. As such, you can't have the same two points in your set of x values.
I am trying to plot step responses in MATLAB and cannot figure it out for anything, I have graphed a Bode plot for 3 different k values for the following differential equation in time domain:
d^2y(t)/dt + (v/m)dy(t)/dt + (k/m)y(t) = (k/m)x(t)
in frequency the equation is:
H(jw)=((k/m))/((〖jw)〗^2+(v/m)(jw)+(k/m) )=k/(m(〖jw)〗^2+v(jw)+k)
the values of k are 1, 0.09, 4
The equations to solve for v is as follows:
v=sqrt(2)*sqrt(k*m) where m=1
I now must do the same for step, but am trying to no avail. Can anyone provide any suggestions?
Here is the code for my Bode plot and my attempted but failed step plots:
w=logspace(-2,2,100);
%Creating different vectors based upon K value
%then calculating the frequencey response based upon
%these values
b1=[1];
a1=[1 2^(.5) 1];
H1=freqs(b1,a1,w);
b2=[.09];
a2=[1 (2^.5)*(.09^.5) .09];
H2=freqs(b2,a2,w);
b3=[4];
a3=[1 2*(2^.5) 4];
H3=freqs(b3,a3,w);
%Ploting frequency response on top plot
%with loglog scale
subplot(2,1,1)
loglog(H1,w,'r')
axis([.04 10 .01 10])
hold on
loglog(H2,w,'g')
loglog(H3,w,'c')
xlabel('Omega')
ylabel('Frequency Response')
title('Bode plot with various K values')
legend('H1, K=1','H2, K=.09','H3, K=4')
hold off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%creating transfer function, how the functions
%respond in time
h1=tf(b1,a1);
h2=tf(b2,a2);
h3=tf(b3,a3);
t=linspace(0,30);
[y1,t1]=step(h1,t);
[y2,t2]=step(h2,t);
[y3,t3]=step(h3,t);
%Ploting step response on bottom plot
%with respect to time
subplot(2,1,2)
plot(t1,abs(y1),'r')
hold on
plot(t2,abs(y2),'g')
plot(t3,abs(y3),'c')
legend('h1, K=1','h2, K=.09','h3, K=4')
xlabel('time(s)')
ylabel('Amplitude')
title('Step response with various K values')
Have you tried using the step function? You already have the coefficients defined in your code above for each of the TFs. step takes in a TF object and gives you the step response in the time domain.
First, take those coefficients and create TF objects. After, run a step response. Using the code you already provided above, do something like this:
b=[1];
a=[1 2^(.5) 1];
% I would personally do: a = [1 sqrt(2) 1];
H1=tf(b, a); % Transfer Function #1
b=[.09];
a=[1 (2^.5)*(.09^.5) .09];
% I would personally do a = [1 sqrt(2*0.09) 0.09];
H2=tf(b, a); % Transfer Function #2
b=[4];
a=[1 2*(2^.5) 4];
% I would personally do a = [1 2*sqrt(2) 4];
H3=tf(b, a); % Transfer Function #3
% Plot the step responses for all three
% Going from 0 to 5 seconds in intervals of 0.01
[y1,t1] = step(H1, 0:0.01:5);
[y2,t2] = step(H2, 0:0.01:5);
[y3,t3] = step(H3, 0:0.01:5);
% Plot the responses
plot(t1, y1, t1, y2, t3, y3)
legend('H1(s)', 'H2(s)', 'H3(s)');
xlabel('Time (s)');
ylabel('Amplitude');
This is the figure I get:
FYI, powering anything to the half is the same as sqrt(). You should consider using that instead to make your code less obfuscated. Judging from your code, it looks like you are trying to modify the frequency of natural oscillations in each second-order underdamped model you are trying to generate while keeping the damping ratio the same. As you increase k, the system should get faster and the steady-state value should also become larger and closer towards 1 - ensuring that you compensate for the DC gain of course. (I'm a former instructor on automatic control systems).
I'm using the Matlab function "hist" to estimate the probability density function of a realization of a random process I have.
I'm actually:
1) taking the histogram of h0
2) normalizing its area in order to get 1
3) plotting the normalized curve.
The problem is that, no matter how many bins I use, the histogram never start from 0 and never go back to 0 whereas I would really like that kind of behavior.
The code I use is the following:
Nbin = 36;
[n,x0] = hist(h0,Nbin);
edge = find(n~=0,1,'last');
Step = x0(edge)/Nbin;
Scale_factor = sum(Step*n);
PDF_h0 = n/Scale_factor;
hist(h0 ,Nbin) %plot the histogram
figure;
plot(a1,p_rice); %plot the theoretical curve in blue
hold on;
plot(x0, PDF_h0,'red'); %plot the normalized curve obtained from the histogram
And the plots I get are:
If your problem is that the plotted red curve does not go to zero: you can solve that adding initial and final points with y-axis value 0. It seems from your code that the x-axis separation is Step, so it would be:
plot([x0(1)-Step x0 x0(end)+Step], [0 PDF_h0 0], 'red')