Vertical lines for Bode plots in Matlab - matlab

I have graphed a Bode plot for my transfer function, and I was wondering if there is some way to insert either horizontal or vertical lines to show a specific value for the gain/phase angle or frequency?
I have found with the following code I can draw a horizontal line on the phase angle graph:
x = linspace(10^-1,10^2,100);
for bleh = 1:length(x)
y(bleh) = -30.9638;
end
bode(num, den)
hold on
plot(x,y)
But this does not seem to apply in the gain graph, nor does my limited knowledge (and only way that makes sense to me) of vertical lines. I tried:
y1 = get(gca,'ylim');
w1 = 1.2;
bode(num, den)
hold on
plot(x,y,[w1 w1],y1)
But I only get the one horizontal line as was done from the above code.
Is this a possibility?
(Using R2017a, if that matters.)

I'm not sure I've understood you question, nevertheless, I propose the following.
When there are more one axes in a figure, as it is the case of the bode diagram, if you want to add something in a specific axes (or in all) you have to specify, in the call to plot the handle of the axes.
So, to add lines in the bode diagram, you have first to identify the handles of the two axes: you can do it in, at least two way:
using the findobj function: ax=findobj(gcf,'type','axes')
extract them as the Children of the figure: ax=get(gcf,'children')
Once you have the handles of the axes, you can get their XLim and YLim that you can use to limit the extent of the line you want to add.
In the following example, I've used the above proposed approach to add two lines in each graph.
The horizontal and vertical lines are added in the middle point of the X and Y axes (problably this point does not have a relevant meaning, but it is ... just an example).
% Define a transfer function
H = tf([1 0.1 7.5],[1 0.12 9 0 0]);
% PLot the bode diagram
bode(H)
% Get the handles of the axes
ax=findobj(gcf,'type','axes')
phase_ax=ax(1)
mag_ax=ax(2)
% Get the X axis limits (it is the same for both the plot
ax_xlim=phase_ax.XLim
% Get the Y axis limits
phase_ylim=phase_ax.YLim
mag_ylim=mag_ax.YLim
%
% Define some points to be used in the plot
% middle point of the X and Y axes of the two plots
%
mid_x=(ax_xlim(1)+ax_xlim(2))/2
mid_phase_y=(phase_ylim(1)+phase_ylim(2))/2
mid_mag_y=(mag_ylim(1)+mag_ylim(2))/2
% Set hold to on to add the line
hold(phase_ax,'on')
% Add a vertical line in the Phase plot
plot(phase_ax,[mid_x mid_x],[phase_ylim(1) phase_ylim(2)])
% Add an horizontal line in the Phase plot
plot(phase_ax,[ax_xlim(1), ax_xlim(2)],[mid_phase_y mid_phase_y])
% Set hold to on to add the line
hold(mag_ax,'on')
% Add a vertical line in the Magnitide plot
plot(mag_ax,[mid_x mid_x],[mag_ylim(1) mag_ylim(2)])
% Add an Horizontal line in the Magnitide plot
plot(mag_ax,[ax_xlim(1), ax_xlim(2)],[mid_mag_y mid_mag_y])
Hope this helps,
Qapla'

Related

Plot multiple columns with different colors in MATLAB

I have a 372x15 matrix. I'm trying to graph this in such a way that columns 1-14 will be on the x-axis with different colors for each column, whereas the 15th column will be treated as the y-axis. For example, the plot with follow (x1, y), (x2, y) so on so forth, where x1 is all the data points in column 1. This is a simple scatterplot. How can I do this on MATLAB?
A simple way to do that is just use plot(A(:,1:end-1), A(:,end), '.'). Here's an example:
A = [(1:14)-.6*rand(372,14) ((1:372).'+rand(372,1))]; % example A. Uses implicit expansion
plot(A(:,1:end-1), A(:,end), '.') % do the plot
axis tight % optionally make axis limits tight
The above cycles through the 7 predefined colors. If you prefer to customize the colors, set the 'ColorOrder' property of the axes before calling plot, and use hold on to prevent Matlab from resetting it:
clf % clear figure
cmap = autumn(size(A,2)); % example colormap
set(gca, 'ColorOrder', cmap); % set that colormap
hold on % needed so that the colormap is not automatically reset
plot(A(:,1:end-1), A(:,end), '.')
axis tight
You can specify different markers or marker sizes; see plot's documentation.

How to add a regression line to a scatter plot in MATLAB

I am trying to add a regression line onto a plot in MATLAB.
this is the code I have:
errorbar(x,y,SEM,'o')
hold on % Retains current plot while adding to it
scatter(x,y)
title('The Effect of Distance Between Images on the Flashed Face Distortion Effect','FontSize',14); % Adds title
xlabel('Distance (Pixels)','FontSize',12); % Adds label on the x axis
ylabel('Average Distortion Rating','FontSize',12); % Adds label on the y axis
hold off
And this is my code for a regression:
mdl = fitlm(x,y,'linear');
Could anyone tell me how to combine the two so i get the regression line on the plot?
I am using psychtoolbox on MATLAB on Windows.
Thanks!
Before the hold off statement, add the following lines:
xf = [min(x), max(x)];
plot(xf, polyval(polyfit(x,y,1), xf));
You may want to decorate your plot call with supplemental arguments setting the line style, and no additional toolboxes are required.

MATLAB: a better way to switch between primary and secondary y-axis?

I'm aware of plotyy but in my opinion it's not as intuitive as for example typing subplot(2,3,1) and from that point one working in that particular subplot's environment...
Suppose I have the following data:
a=rand(20,1);
a_cumul=cumsum(a);
I would like to do a plot of a_cumul on the primary (left hand) y-axis and a bar chart of a on the secondary (right hand) y-axis.
I'm well aware that I can do:
plotyy(1:length(a_cumul),a_cumul,1:length(a),a,'plot','bar')
But this is cumbersome and what if I want to for example plot to the secondary y-axis only and not plot to the primary y-axis? In short, I'm looking for whether a solution like this exists:
figure;
switchToPrimaryYAxis; % What to do here??
plot(a_cumul);
% Do some formatting here if needed...
switchToSecondaryYAxis; % What to do here??
bar(a);
Thanks a lot for your help!
Basically plotyy:
creates two superimposed axes
plots the data specified as the first two params on the first axes
plots the data specified as the last two params on the second axes
set the second second axes color to none making it "transparent" so allowing seeing the graph on the first axes
moves the yaxislocation from the standard position (left) to right
You can create a figure, then two axes make make any plot on the two axes by selecting then with axes(h) where h is the handler of the axes.
Then you can write a your own function performing the axes adjustment.
Script to create figure, axes and call the function to adjust the axes
% Generate example data
t1=0:.1:2*pi;
t2=0:.1:4*pi;
y1=sin(t1);
y2=cos(t2);
% Create a "figure"
figure
% Create two axes
a1=axes
a2=axes
% Set the first axes as current axes
axes(a1)
% Plot something
plot(t1,y1,'k','linewidth',2)
% Set the second axes as current axes
axes(a2)
% Plot something
plot(t2,y2,'b','linewidth',2)
grid
% Adjust the axes:
my_plotyy(a1,a2)
Function to adjust the axes - emulating plotyy behaviour
The function requires, as input, the handles of the two axes
function my_plotyy(a1,a2)
set(a1,'ycolor',[0 0 0])
set(a1,'box','on')
% Adjust the second axes:
% change x and y axis color
% move x and y axis location
% set axes color to none (this make it transparend allowing seeing the
% graph on the first axes
set(a2,'ycolor','b')
set(a2,'xcolor','b')
set(a2,'YAxisLocation','right')
set(a2,'XAxisLocation','top')
set(a2,'color','none')
set(a2,'box','off')
Hope this helps.

How to merge different plot but same y axis in matlab

I'm always see this kind of graph in XRD plot:
and i'm wondering how they do that?, if you have different XRD plot and assuming having the same y axis, can matlab do this? thanks.
Here is a way to do it.You can customize it as you want, but this should hopefully get you going.
First create an axes and change its position/size inside the figure, shifting it upward to make room for the 2nd axes as well as removing the x and y labels that you don't want. Then create a 2nd axes with specified position/size to make it fit below the 1st one.
Sample code:
clear
clc
%// Generate dummy data
x = 1:2:100;
y1 = rand(1,numel(x));
figure;
%// Make an axes and set its position
haxes1 = axes('Position',[.1 .1 .8 .7],'Color',[1 1 1])
%// Plot 1st curve
plot(x,y1,'Parent',haxes1)
%// Remove box and labels
box off
set(gca,'XTickLabel','','XTick',[],'YTick',[])
hold on
%// Get current axes position. You set it so you could get the parameters
%// directly as well.
axes1Pos = get(gca,'Position');
%// Shift 1st axes upward
set(gca,'Position',[axes1Pos(1) 2.6*axes1Pos(2) axes1Pos(3) axes1Pos(4)])
%// Change the poisition/size of the 2nd axes to fit below the 1st one
haxes2 = axes('Position',[axes1Pos(1) axes1Pos(2)/2.5 axes1Pos(3) axes1Pos(4)/2.5]) ;
%// Use linspace to generate colored points to use with scatter.
c = linspace(1,10,length(x));
%// Add 2nd plot and keep only x label
scatter(x,rand(1,numel(x)),40,c,'filled')
set(gca,'YTick',[])
box off
%// Place a ylabel for both axes
text(-4, 1.7,'Super nice y label','rotation',90,'FontSize',16,'HorizontalAlignment','center')
Sample output:
There are other ways to do this as well.
Hope that helps!

Matlab: Plot3 not showing the 3rd axis

All the three variables I am using to plot are matrix of size 1x1x100. I am using this code line to plot:
hold on;
for i=1:100
plot3(R_L(:,:,i),N_Pc(:,:,i),CO2_molefraction_top_of_window(:,:,i),'o');
xlabel('R_L');
ylabel('N_P_c');
zlabel('CO_2')
end
However, I am not getting the third axis, and hence the third variable CO2_molefraction_top_of_window on the plot. May I know where am I wrong?
Besides the above question, but on the same subject, I want to know if there is any option where I can plot 4 dimensional plot just like the 3 dimensional plot which can be drawn using plot3?
So I had the same problem when using plot3. For some reason, using the hold on command "flattens" the plot. I'm not sure why, but I suspect it has something to do with the operation hold on performs on the plot.
Edit: To clarify, the 3d plot is still there, but the perspective has been forced to change. If you use the "rotate 3D" tool (the one with an arrow around a cube), you can see the graph is 3d, the default perspective is just straight on so only two axes are visible and it appears flat.
Just a note --- you only need to do the xlabel ylabel zlabel commands once (outside the loop).
Also:
is there any reason your matrices are 1x1x100 instead of just 100x1 or 1x100?
Because if you reshape them to 2D you can just do the plotting in one hit.
What do you mean by "missing third axis"? When I run your code (or as close as I can get, since you didn't provide a reproducible example), I do get a 3rd axis:
.
X = rand(1,1,100); % 1x1x100 X matrix
Y = rand(1,1,100); % 1x1x100 Y matrix
Z = rand(1,1,100); % 1x1x100 Z matrix
% Now, we could do a for loop and plot X(:,:,i), Y(:,:,i), Z(:,:,i),
% OR we can just convert the matrix to a vector (since it's 1x1x100 anyway)
% and do the plotting in one go using 'squeeze' (see 'help squeeze').
% squeeze(X) converts it from 1x1x100 (3D matrix) to 100x1 (vector):
plot3(squeeze(X),squeeze(Y),squeeze(Z),'o')
xlabel('x')
ylabel('y')
zlabel('z')
This gives the following, in which you can clearly see three axes:
If it's the gridlines that you want to make the graph look "more 3D", then try grid on (which is in the examples in the Matlab help file for plot3, try help plot3 from the Matlab prompt):
grid on
You will have to clarify "missing third axis" a bit more.
I came across a similar problem and as #Drofdarb's the hold on seems to flatten out one axis. Here is a snippet of my code, hope this helps.
for iter = 1:num_iters:
% hold on;
grid on;
plot3(tita0,tita1, num_iters,'o')
title('Tita0, Tita1')
xlabel('Tita0')
ylabel('Tita1')
zlabel('Iterations')
hold on; % <---- Place here
drawnow
end
As opposed to:
for iter = 1:num_iters:
grid on;
hold on; % <---- Not here
plot3(tita0,tita1, num_iters,'o')
title('Tita0, Tita1')
xlabel('Tita0')
ylabel('Tita1')
zlabel('Iterations')
% hold on;
drawnow
end