How to plot two figures in MATLAB - 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

Related

MATLAB: Blanked Plots when Looping on a Multidimensional Array

My goal output is to have four plots displaying (time, dist_a), (time, speed_a), (time, dist_b), and (time, speed_b) when looping through a multidimensional array. However, I am displaying only 2 blanked plots.
Here is my code:
time = rand(10, 1)
dist_a = rand(10,1)
dist_b = rand(10,1)
speed_a = rand(10,1)
speed_b = rand(10,1)
dist = cat(2, dist_a, dist_b);
speed = cat(2, speed_a, speed_b);
for k = 1:2
figure;
plot(time, dist(k));
plot(time, speed(k));
end
Your problems were two-fold. Firstly, you were only plotting a single point as opposed to a vector, changing dist(k) to dist(:,k) for example fixes this. Secondly, if you want four figures with a loop that executes twice, you need to include another figure command before the second plot. The following should do what you asked for, I also added in some formatting to make the plots looks nicer
for k = 1:2
figure
plot(time, dist(:,k),'o','LineWidth',2);
xlabel('time')
ylabel('distance')
box on
grid on
figure
plot(time, speed(:,k),'o','LineWidth',2);
xlabel('time')
ylabel('speed')
box on
grid on
end
which gives:

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.

MATLAB: plotting subplots in for loop

I'm trying to plot several subplots in a single figure.
The total number of subplots is dependent on the maximal value in a matrix: maximal value of 'i'.
I'd like to plot two variables in two subplots below each other for every value of i :slagtijd_start & slagfrequentie_start
So when the maximum value of i = 3, we have a subplot matrix of 2x3 axes,
if i = 4 --> 2x4 axes etc.
Plotting on the right postions works, except that matlab erases the previous subplots (previous values of i). In this case i = 3 and the figure only displays the two latest subplots. I've tried different things with 'hold on' etc. But I can't figure it out. It's probably a simple trick.
I've posted my code and resulting figure below,
Thanks in advance,
Mochje
figure(6)
hold on
for i = 1:max(piektijden_start(:,2))
startnummer = find(piektijden_start(:,2) == i);
slagtijd_start= diff(piektijden_start(startnummer));
slagfrequentie_start= (60./slagtijd_start);
subplot(2,i,i),plot(piektijden_start(startnummer(1:end-1),1),slagtijd_start)
hold on
xlabel('Tijd [s]')
ylabel('Slagtijd [s]')
title('Slagtijd')
subplot(2,i,i+i),plot(piektijden_start(startnummer(1:end-1),1),slagfrequentie_start)
hold on
plot(piektijden_start(startnummer(1:end-1),1),slagfrequentie_start,'.r')
xlabel('Tijd [s]')
ylabel('Slagfrequentie [N/min]')
title('Slagfrequentie')
end
Use something like
figure(6)
hold on
max_i = max(piektijden_start(:,2));
for i = 1:max_i
%// ...
subplot(2, max_i, i)
%// ...
subplot(2, max_i, i+max_i)
%// ...
end
The second argument to subplot is the number of subplot columns. The third is the addressed subplot, such that such that the first subplot is the first column of the first row, the second subplot is the second column of the first row, and so on

How to add new plots of different scale to an existing histogram?

I have a Matlab figure with two histograms on it
,
created with hist() function. Now I want to add two plots in the same figure (bell distribution actually:
,
but they have different scale. I thought I could use plotyy, but I already have my first plot-scale on the figure. How can I add the second plot-scale?
Generally, this is one way to do it:
%// example data
rng(0,'twister')
data = randn(1000,3);
x = linspace(-4,4,100);
y = 16 - x.^2;
%// generate two axes at same position
ax1 = axes;
ax2 = axes('Position', get(ax1, 'Position'),'Color','none');
%// move second axis to the right, remove x-ticks and labels
set(ax2,'YAxisLocation','right')
set(ax2,'XTick',[])
%// plot hist and line plot
hist(ax1,data); hold on
plot(ax2,x,y)
ylabel(ax1,'label of hist')
ylabel(ax2,'label of plot')
xlabel(ax1,'Hello World!')

How do I reach first and second plots from bode()

I know how to create the Bode plots with bode() function. If I want to overlap two or more systems frequency responses, I use
bode(sys1,sys2,...)
or
hold on
When I want to reach the plot in order to put a legend with text(), for instance, is easy to reach the second plot. Something like the figure pointer always returns to the second plot (phase graph).
i.e., if try these lines:
G = tf([1],[1 6]); figure(1); bode(G); text(10,-20,'text');
G = tf([1],[1 6]); figure(2); bode(G); text(10,-20,'text');
when I return to the first figure, with figure(1), and try
figure(1); text(10,-20,'text')
legend is displayed in the second plot (Phase plot)
I try these other lines:
P = bodeoptions; % Set phase visiblity to off
P.PhaseVisible = 'off';
G = tf([1],[1 6]);
figure(1); bode(G,P); text(10,-20,'text');
figure(1); text(10,-20,'text');
As you can see, even I turn off the phase plot visiblity, the legend is not displayed.
Essentialy, my question is, how do I reach first and second plots, one by one? I tried with subplot(), but it is pretty clear this is not the way Matlab traces these plots.
Thanks in advance.
It all comes to getting into upper plot, since after bodeplot command the lower one is active. Intuitively one would want to call subplot(2,1,1), but this just creates new blank plot on top of if. Therefore we should do something like this:
% First, define arbitrary transfer function G(s), domain ww
% and function we want to plot on magnitude plot.
s = tf('s');
G = 50 / ( s*(1.6*s+1)*(0.23*s+1) );
ww = logspace(0,3,5000);
y = 10.^(-2*log10(ww)+log10(150));
hand = figure; % create a handle to new figure
h = bodeplot(G,ww);
hold on;
children = get(hand, 'Children') % use this handle to obtain list of figure's children
% We see that children has 3 objects:
% 1) Context Menu 2) Axis object to Phase Plot 3) Axis object to Magnitude Plot
magChild = children(3); % Pick a handle to axes of magnitude in bode diagram.
% magChild = childern(2) % This way you can add data to Phase Plot.
axes(magChild) % Make those axes current
loglog(ww,y,'r');
legend('transfer function','added curve')
you can get magnitude and phase data separately for each system using:
[mag,phase] = bode(sys,w)
now you can use subplot or plot to plot the diagram you want.
The only solution I was able to perform is taking into account axis position. It is not very clean but it works.
Here is the code to select mag plot:
ejes=findobj(get(gcf,'children'),'Type','axes','visible','on');
posicion=get(ejes,'pos');
tam=length(posicion);
for ii=1:tam
a=posicion{ii}(2);
vectorPos(ii)=a;
end
[valorMax,ind]=max(vectorPos); % min for choosing the phase plot
axes(ejes(ind))