How to connect points on a Matlab plot? - matlab

I wrote the code to get the relationship between the two variables. The code is as follows:
for fn=0.1:0.1:10
for Qe= [0.1,0.5, 1, 5]
fn2=fn.*fn;
Mg=abs((Ln*fn2)/(((Ln+1)*(fn2)-1)+1i*(((fn2)-1).*fn.*Qe*Ln)));
semilogx(fn,Mg,'b','linewidth',7);
hold on;
save;
end
end
However, The curves I got are scatters points. I want to get all points to be connected. When I increase the step point for fn, i.e fn=0.1:0.001:10, it is better, but it takes a very long time.

Your problem is that you plot a single point every iteration. Let the loops run their course, save the points as vectors, then call a single plot at the end plotting the vectors, which will automatically generate connected lines.
fn=0.1:0.1:10
Qe= [0.1,0.5, 1, 5]
Mg = zeros(numel(fn),numel(Qe)); %initialise output
for ii=1:numel(fn)
fn2=fn(ii)^2;
for jj = 1:numel(Qe)
Mg(ii,jj)=abs((Ln*fn2)/(((Ln+1)*(fn2)-1)+1i*(((fn2)-1).*fn(ii).*Qe(jj)*Ln))); %save in matrix form
end
end
figure
hold on;
semilogx(fn,Mg(:,1),'b','linewidth',7); % Generate plots with different colours
semilogx(fn,Mg(:,2),'r','linewidth',7);
semilogx(fn,Mg(:,3),'y','linewidth',7);
semilogx(fn,Mg(:,4),'g','linewidth',7);

I could solve it using this code. It could solve the problem, however, it is a little bit slow (
%%Parameters%%
Ln=8;
Mgmin=0.88;
Mgmax=1.18;
Qe= [0.25,0.3,0.35,0.7,1.65,4,8];
c= {'b','m','r','g','y','c','k'};
%%Gain Vs Frequecny Function%%
fn=0.1:0.001:10;
fn2=fn.*fn;
%%Gain Curve%%
figure;
for j=1:7
for i=1:9901
Mg(i)=abs((Ln*(fn2(i)))/(((Ln+1)*(fn2(i))-1)+1i*(((fn2(i))-1).*fn(i).*Qe(j)*Ln)));
end;
semilogx(fn,Mg,c{j},'linewidth',3);
hold on;
plot(fn,Mgmax,'k');
hold on;
plot(fn,Mgmin,'k');
save;
end;

Related

Handling and eliminating multiples entries in MatLab legend

I currently want to have the legend of graph, however i'm plotting several lines that should be group in only 3 types.
My currently option is to use a dummy plot out of the boundaries, plotting the relevant data and calling the legend just at the end. It works but it is prone to errors. I wanted to update the legend and select just a few of the plots.
I tried to use the leg_handle.String, but then it comes two problems:
It still plot 5 handles instead of 3.
It does not have the proper line style & color.
Any ideas?
Bellow follow the code (with dummy plot commented) and the pictures of the current version giving the error and what i want to look.
clear
figure()
hold on
%using
%dummy plot
% leg_text={'a','b','c'};
% plot(100,100,'-r')
% plot(100,100,'-b')
% plot(100,100,'-k')
for ii=1:20,
plot(1:11,linspace(0,ii,11),'-r')
end
for ii=30:50,
plot(1:11,linspace(0,ii,11),'-b')
end
for ii=70:80,
plot(1:11,linspace(ii,25,11),'-k')
end
Yaxl=[-1 80];
Xaxl=[1 11];
set(gca, 'Visible','on', ...
'Box','on', ...
'Layer','top',...
'Xlim',Xaxl, ...
'Ylim',Yaxl);
%using
% legend(leg_text)
%want to use
leg_hand=legend(gca,'show');
leg_hand.String=leg_hand.String([1 21 42]);
%extra comand will give the things that i wanted above
% leg_hand.String=leg_hand.String([1 2 3]);
What it gives:
What I expect to have:
I have tried this method using [a,b,c,d]=legend, but this give only the a handle that i already using.
This little workaround should do the job:
clear();
figure();
hold on;
h = gobjects(3,1);
for ii = 1:20
h(1) = plot(1:11,linspace(0,ii,11),'-r');
end
for ii = 30:50
h(2) = plot(1:11,linspace(0,ii,11),'-b');
end
for ii = 70:80
h(3) = plot(1:11,linspace(ii,25,11),'-k');
end
set(gca,'Box','on','Layer','top','Visible','on','Xlim',[1 11],'Ylim',[-1 80]);
legend(h,'A','B','C');
hold off;
Actually, what I did is very simple. I created an array of graphical objects of size 3 (one for each iteration) using the gobjects function. Then, inside each iteration, I assigned the last plotted line to its respective array placeholder. Finally, I created the legend using the three graphical objects I previously stored.
Alternatively:
clear();
figure();
hold on;
h1 = gobjects(20,1);
for ii = 1:20
h1(ii) = plot(1:11,linspace(0,ii,11),'-r');
end
h2 = gobjects(21,1);
for ii = 30:50
h2(ii-29) = plot(1:11,linspace(0,ii,11),'-b');
end
h3 = gobjects(11,1);
for ii = 70:80
h3(ii-69) = plot(1:11,linspace(ii,25,11),'-k');
end
set(gca,'Box','on','Layer','top','Visible','on','Xlim',[1 11],'Ylim',[-1 80]);
legend([h1(1) h2(1) h3(1)],'A','B','C');
hold off;
You create an array of graphical objects for storing the plot handlers produced by every iteration. Then you create the legend using the first (basically, any) item of each array of graphical objects.

How to animate points on an image in MATLAB?

I have the pixel locations of P points on a -constant- image, for T iterations of an algorithm, so locations = [T x 2*P] double.
Now I want to create an animation where it plots the image, then plots the points, pauses for N seconds and updates their location to the next step. I don't know if there is a standard way to follow. I think I need something like:
figure;
imshow(img);
hold on;
for t=1:T
anim = updatePlot(locations(t,:), anim); % ?
end
How can I implement this updatePlot function?
Thanks for any help!
You can do this a couple of different ways. The first way would be to give the plotted points a handle so that you can delete them before the next iteration:
figure
imshow(img);
hold on;
for t = 1:T
% delete the previous points plotted (skip t = 1 since they won't exist)
if t > 1
delete(hPoints);
end
hPoints = plot(xLocations(t,:),yLocations(t,:),'.');
getframe;
pause(N);
end
(I am not exactly sure how you parse your locations along each row to separate the x and y components, so I've just used xLocations and yLocations to represent those values.)
The second way would be to re-draw the entire image at each iteration:
figure
for t = 1:T
clf;
imshow(img);
hold on;
plot(xLocations(t,:),yLocations(t,:),'.');
getframe;
pause(N);
end
Note that imshow might have its own getframe effect so that you'll see the image flicker before plotting the points -- if that happens just switch from imshow to image.

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

Append figure with new plots

I want to visualize two sets of data in different figures. Here is how do I realize it now:
f1 = figure;
for i=0:6
plot(stim(i)+i);
hold on;
end;
f2 = figure;
for i=0:6
plot(data(i)+i);
hold on;
end;
I think there have to be the way to combine these loops.
Sure. As per Matlab reference: first you create empty figures and do the hold-on (you don't need to do it every time):
f1 = figure;
hold on
f2 = figure;
hold on
Then you loop:
for i=0:6
figure(f1)
plot(stim(i)+i);
figure(f2)
plot(data(i)+i);
end
This time the figures are already created; calling figure here therefore switches the active figure so you can plot on it;
And without for loops, something like this:
idx = (0:6).';
figure(f1);
plot(stim(idx)+idx);
figure(f2);
plot(data(idx)+idx);
Make sure that you apply the solution to the right dimension. The column vectors are interpreted as one dataset; And for points, remember to set the markers.

How to plot two figures in MATLAB

I am implementing a clustering algorithm for n data points and I want to plot n data points in a figure before clustering and in another figure after clustering meaning that there should be two figures in same file with same data points.
My code is like:
X = 500*rand([n,2]);
plot(X(:,1), X(:,2), 'r.') 1
%Some coding section here
After:
symbs = {'r+','g.','bv','m*','ko'};
hold on
for i = 1: length(I)
plot(X(C==i,1), X(C==i,2), symbs{i}) 2
end
I just want to plot (1) in one figure and (2) in another.
Try subplot:
figure;
subplot(1,2,1)
plot(firstdata)
subplot(1,2,2)
plot(seconddata)
This will create two axes areas within the same figure window... from your description, this is my best guess as to what you want.
Edit: From the comments below, here is what you are doing
n=50;
X = 500*rand([n,2]);
subplot(1,2,1); #% <---- add 'subplot' here
plot(X(:,1),X(:,2),'r.')
symbs= {'r+','g.','bv','m*','ko'};
subplot(1,2,2); #% <---- add 'subplot' here (with different arguments)
hold on
for i = 1: length(I)
plot(X(C==i,1),X(C==i,2),symbs{i})
end
If all you want is a second figure window, instead of doing subplot you can simply say figure in the place where I put the second call to subplot and a new figure window will be created.
figure; #% <--- creates a figure window
n=50;
X = 500*rand([n,2]);
plot(X(:,1),X(:,2),'r.') #% <--- goes in first window
symbs= {'r+','g.','bv','m*','ko'};
figure; #% <---- creates another figure window
hold on
for i = 1: length(I)
plot(X(C==i,1),X(C==i,2),symbs{i}) #% <--- goes in second window
end
You just need to add figure before each plot to get two plots in two separated figures