Plot two figures on the same figure using subplot [duplicate] - matlab

This question already has an answer here:
How does subplot work and what is the difference between subplot(121) and subplot(1,2,1) in MATLAB?
(1 answer)
Closed 8 years ago.
I am trying to plot the following using subplot how can I do that? Thank you
[n,wc]= buttord(Wp,Ws,Rp,Rs);
[z,p,k]=butter(n,wc);
sos = zp2sos(z,p,k);
freqz(sos) ;
grpdelay(sos) ;
Note that this is non-trivial since freqz yields a subplot already.

The following would work if the functions you are using plotted one figure each: call subplot right before each function that produces a graphic output. It is kind of straightforward from the manual, subplot(m,n,p) splits the figure into a grid of m x n graphics and draws the p-th one. However, as pointed by #hbaderts, freqz produces a subplot of its own, so you would need to rearrange it to include the upcoming output of grpdelay.
This is how you could do it, as per the workaround proposed in this thread (see it for the more general solution).
freqz(sos);
h = get(gcf, 'children');
fig2=figure;
figure(fig2)
g=subplot(3,1,1)
set(h(1), 'pos', get(g, 'pos'))
figure(fig2)
g=subplot(3,1,2)
set(h(2), 'pos', get(g, 'pos'))
close
g=subplot(3,1,3)
grpdelay(sos)

Probably the easiest solution is calculating the frequency response with freqz and plotting it with freqzplot. This is not the best solution because freqzplot is obsolete. A better solution would be to manually create the plots (e.g. 20*log10(abs(h))).
[h,w] = freqz(sos);
subplot(2,2,1);
freqzplot(h,w,'mag');
subplot(2,2,3);
freqzplot(h,w,'phase');
subplot(2,2,[2,4]);
grpdelay(sos);

Related

Color along line in MATLAB polaraxes

I am trying to combine two "solved" aspects of MATLAB -- 1) plotting a 2D line with color that varies along the line in 2) polar axes.
The first part is usually easy, and frequently asked:
https://www.mathworks.com/matlabcentral/answers/5042-how-do-i-vary-color-along-a-2d-line or
How to vary the line color of a matlab plot (like colormap)?
The most commonly suggested trick is to use surf or mesh to create a "fake" 3D line and color this. However, this is not supported on polaraxesin MATLAB:
>> polaraxes, hold on;
>> surf([1 1; 1 1], [2 2; 2 2], [3 3; 3 3])
Error using newplot (line 80)
Adding Cartesian plot to polaraxes is not supported.
One trick that does seem to work is using a sequence of line segments, as is done in cline.m from File Exchange. http://www.mathworks.com/matlabcentral/fileexchange/3747-cline-m
>> polaraxes; hold on; cline;
Gives this
which is technically what I want... but as pointed out in the previous comments, is much uglier than the solution with surf or mesh since it draws individual segments.
Is there any other way to do this? I found this question also asked here
https://www.mathworks.com/matlabcentral/answers/439176-how-do-i-vary-the-color-along-a-line-in-polar-coordinates
with an "accepted answer" that this does not seem possible, so I'm feeling a little pessimistic.
Cross-posting the answer from Chad Greene here
https://www.mathworks.com/matlabcentral/answers/822360-color-along-line-in-polaraxes#answer_692780
theta = linspace(0,6*pi,100000);
rho1 = theta/10;
polarscatter(theta,rho1,5,rho1,'filled')
Looks as good as its going to get, I think.
One way to make it "prettier" and not use so few lines is to increase the number of lines that is used to plot the line. I looked into the file of cline and where x is assigned with 101 points is where you could modify it to get the example to be prettier so that it doesn't look like it is built with straight lines, even if it is so.
So by changing x=linspace(-10,10,101) to x=linspace(-10,10,1001) the example polaraxes; hold on; cline; gets prettier. This means that you could still use cline with your own values of x, y, z, c and get a pretty polaraxes with your choice of colormap if you make the lines small enough, e.g. many points in your interval for x.

How can I plot professional quality graphs in matlab? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
The default graphs produced from matlab are very different from what I see in books. For example the image below looks visually pleasing. Can I change default settings of matlab to mimic this graphing style?
This question will refrain from lecturing the OP on best practices for graphics and simply attempt to answer the question as asked. I personally concur with a few of the concerns raised but leave it to the OP to seek out resources on data visualization and graphical aesthetics. (For the record, I'm not a fan of the chart.)
Resources:
The MATLAB Plot Gallery depicts a range of plots and adjustments that may help you. For high quality, professional looking graphs, scroll down to the Advanced Plots to see source code and the resulting figures.
Graphical overview of the Types of MATLAB Plots available.
You can also make a basic plot then use MATLAB's Plot Editor to customize the properties through the graphical interface. When done, click File-->Generate Code and you'll see one possible way to code that graph. This is helpful when you know how to do something through the interface but want to script it in the future.
Examples with code for Publication Quality Plots with Matlab
Mathworks blog on Making Pretty Graphs
Another example on Creating high-quality graphics in MATLAB for papers and presentations
I realize some of these links may eventually expire. Please feel free to comment if they do
Example:
I'm no expert. I learned everything in this answer from looking at the documentation, plot source code, and playing with the properties for the various plot components.
% Functions of Interest % MATLAB 2018a
fh=#(x) a + a*sin(b*x) + 1-exp(-b*x);
gh=#(x) a + (a/b)*cos(c*x);
a = 20;
b = .3;
c = .2;
% Plot
X = (0:.01:25)';
figure, hold on
p(1) = plot(X,fh(X),'r-','DisplayName','Excitation')
p(2) = plot(X,gh(X),'b-','DisplayName','Recovery')
% legend('show') % Optional legend (omitted here since we're adding text)
xlabel('X')
ylabel('Y')
title('Particle Displacement')
% Options
ha = gca;
box on
grid on
ylim([-80 100])
set(ha,'GridLineStyle','--') % use ':' for dots
t(1) = text(3.5,80,'excitation')
t(2) = text(12,20,'recovery')
for k = 1:2
p(k).LineWidth = 2.2;
t(k).FontWeight = 'bold';
t(k).FontSize = 12;
t(k).FontName = 'Arial';
end
Create a function which takes a matrix of data where each row represents a signal that you want to plot.
Define some styles you want to use for plotting. In your example plot, the first two would be 'bo' and 'rx'. Just iterate over your rows and plot each row with a different style followed by the command "hold on;"
function fancyplot(xaxis, matrix)
figure;
style = {'bo', 'rx', 'k.'}; # and so on
for r = 1:size(matrix, 1)
plot(xaxis, matrix(r,:), style{r});
hold on;
end
end
Write another script which you execute right after you plot or add it to the function above. In this script use the the following methods to control the limits of the axis
xlim
ylim
Set them to the min/max values of the data you plotted.
To add text to your plots use the Text command.
If you want to use these plots in publications be mindful of the fact that most publications are black and white and your graphs should be distinguishable event if they are not colored (I doubt the ones above would be). I always believed doing all formatting in code is a good idea without the manual tinkering around. Otherwise you might figure out that you have to update all 8 plots in your publication at 4 am shortly before you need to submit your paper. If you run some simulations and all formatting is in code you can simply execute your formatting scripts and save the plots automatically how to save a picture from code, preferably to the eps format.

Q on plotting function against t and trajectory in phase space(matlab)

I am very beginner for matlab and try to solve this question. But so far it is not successful. I have spent quite a time and I think I need some help. I would appreciate any help!!!
I need to plot v against time and trajectory of v and w in phase space. The whole question is below and my code for previous question connected to this question is also below. I can go with subplot(2,1,1) for the first graph and subplot(2,1,2) for the next graph. But I am not sure what I have to do other than this. I kind of found ode45 command. But not sure how to use it and if it is the right one to use here. I have tried to use ode45. But it shows many errors that I don't understand.....Please help me on this. Thanks a lot!
'Create a figure which contains two graphs, using subplot. In the first graph, plot the temporal evolution of the membrane potential v(t) against time t. In the second graph, plot the corresponding trajectory (v(t); w (t)) in (the so-called) phase space.'
% my code is below.
a=0.08;
b=3.6;
c=0.7;
T=2; % this can be any number
I_ext=20; % this can be any number
dt=0.01; % this can be any number
function [ v,w ] = fhnn( a,b,c,I_ext,T,dt)
v=zeros(1,numel(T/dt));
w=zeros(1,numel(T/dt));
for n=1:numel(T/dt)
v(n+1)=(v(n)-v(n)^3/3-w(n)+I_ext)*dt+v(n);
w(n+1)=a*(v(n)-b*w(n)+c)*dt+w(n);
end
I gather you have a differential equation and are trying to directly plot that. You might find a better approach would be to actually solve the equation if that is possible.
Either way, recognising that:
numel returns the length of an array and dT/dt is always a scalar so the length is always one.
fhnn is not used here.
You still need a vector t.
If what is in your for loop is correct, the following should work:
a=0.08; b=3.6; c=0.7; T=2; I_ext=20; dt=0.01;
t = 0:dt:T;
v = zeros(1,round(T/dt));
w = zeros(1,round(T/dt));
for n=1:round(T/dt)-1
v(n+1)=(v(n)-v(n)^3/3-w(n)+I_ext)*dt+v(n);
w(n+1)=a*(v(n)-b*w(n)+c)*dt+w(n);
end
subplot(2,1,1)
plot(t,v)
xlabel('t')
ylabel('v')
subplot(2,1,2)
plot(v,w)
xlabel('v')
ylabel('w')

Changing the XLim in a cfit plot

I have trouble changing the x-range (XLim) in plots of curve-fit objects.
Preparing a Minimal Example
Let's define noisy data and fit a function to it, using fit from the curve fitting toolbox.
xdata = (0:0.1:1)';
noise = 0.1*randn(size(xdata));
ydata = xdata.^2 + noise;
f = fittype('a*x.^2 + b');
fit1 = fit(xdata, ydata, f, 'StartPoint', [1,1]);
fit1 is now a cfit object and we can plot it using its (overloaded) plot method:
plot(fit1, xdata, ydata)
The Problem
When we now change the XLim of the plot using set(gca, 'XLim', [0,2]), the plot updates but the fit curve is not extended. The documentation suggests that you can do that automagically from within the plot command, but for it does not work for me:
plot(fit1, xdata, ydata, 'XLim', [0, 1])
-> Subscript indices must either be real positive integers or logicals.
-> Error in cfit/plot (line 228)
-> handles = plot(xpoints(~outliers),ypoints(~outliers),S2,...
If I use cftool for the fit (a GUI wrapper for fit), I can enter XLim under Tools->Axes Limits. The fit function is then displayed for the whole range. How can I do this programmatically?
I am aware that you can evaluate the fit function for a given range, but when you have to do that for confidence intervals and several fits, this becomes tedious. I am looking for an easier way, and I think I am just uing the plot command wrong.
The documentation says that when you plot a fit object, it will extrapolate to the current axis limits. It does not redraw the line after you change the plot limits. Further, it appears that when you overload plot it plots the fitdata as the same length as the xdata/ydata. To accomplish your goal, you could do
figure; hold on
plot(xdata,ydata,'.')
ext_xdata = 0:0.1:2;
plot(ext_xdata,fit1.a*ext_xdata.^2 + fit1.b,'r')
But you alluded that the above solution is undesirable for you because of complications of your application. An alternative approach is
figure; hold on
plot(xdata,ydata,'.')
set(gca,'xlim',[0, 2]);
plot(fit1)
This isn't a one line solution like what you seem to be looking for, but it removes the need to specify a new xrange.
The function plot that you use to plot a fit object actually overloads the standard plot function. If you try to set a breakpoint if error (dbstop error), you would see that the actual matlab plot function is called inside the function plotting a fit object. The syntax is then not exactly the same which means that you need to call either xlim([minLim,maxLim]); after you have plotted the function
plot(fit1,xdata, ydata);
xlim([minLim,maxLim]);
I am not sure why this happens since in matlabs documentation they actually state that it should work. This may be a bug which should be reported.

For loop in matlab plot

Hello i am having some problems understading basic plotting in matlab.
I can understand why you would use a for loop when plotting data?
Can anybody explain this to me?
I am making a simple linear plot. Is there any reason this should be inside a loop
If you are making a simple plot there is virtually no reason to use a loop.
If you check doc plot you will find that plot can take some vectors as input, or even matrices for more interesting situations.
Example:
x=0:0.01:1;
y=sin(x);
plot(x,y)
No there is no need in Matlab to use a for loop for plotting. If you are looking for a simple linear plot your code could look like this:
x=1:100;
y=3*x+4;
plot(x,y)
As you see there is no for loop needed. Same goes for nearly all plots and visualization.
A possible reason to use a for loop to plot thing may be having several data to plot in a single matrix. Say you have two matrix Ax (MxN) and Ay (MxN) where N the length of each data and M is the amount of different data wanted to plot. For example like in this case N is 201 and M is 3:
% Create Ax and Ay
Ax=meshgrid(0:0.1:20,1:3);
Ay=zeros(size(Ax));
% Sinusoidals with different frequencies
for k=1:3
Ay(k,:)=sin(k.*Ax(k,:));
end
% create colours
colorVec = hsv(3);
% Plot
hold on
for k=1:3
plot(Ax(k,:),Ay(k,:),'Color',colorVec(k,:))
end
hold off
You get: