MATLAB: What is the difference between pzmap and pzplot? - matlab

What is the difference between pzmap and pzplot ?? Both are used to plot the poles and zeros of the LTI system.
For example:
Lets say I define my transfer function via tf command:
t = tf([2 5],[1 3 2])
Transfer Function
Continuous-time transfer function.
But when I try to plot the zero-pole-map via pzmap, I got:
pzmap(t)
And with pzplot, I got the same plot:
pzplot(t)
Plot with pzmap and pzplot
Both are the same plots. What is the difference then between pzmap and pzplot ??

pzplot allows you to customize your figure. For example, the marker size or line width. An example of how to customize your figure:
close all;clear;clc;
Ts = 1;
num = [1, 0.5, 0, 1]; % b
den = [0, 3, 2, 0]; % a
HZ = tf(num, den, Ts, 'variable', 'z^-1');
pzplot(HZ)
h = findobj(gca, 'type', 'line');
set(h, 'markersize', 9)
text(real(roots(num)) - 0.1, imag(roots(num)) + 0.1, 'Zero')
text(real(roots(den)) - 0.1, imag(roots(den)) + 0.1, 'Pole')
axis equal
However; pzmap command only maps the locations of zeros and poles.
Notice here that marker sizes are larger than default size set by MATLAB.

Related

Solve quadratic equations without individually specifying cofficients

I am trying to solve equations like:
3*(3x-12)/(x+3)-2*(2x+3)/(3x-1) = 5
This is the code that I use:
eqn1 = 3*(3*X-12)/(X+3)-2*(2*X+3)/(3*X-1) == 5;
sol = solve(eqn1, X);
xSol = sol.X
This is the error that I get:
Error using sym/subsref
Too many output arguments.
The first thing I'd suggest is performing a graphical solution:
% Define the function:
f = #(X)3*(3*X-12)./(X+3)-2*(2*X+3)./(3*X-1)-5;
% Plot the function (solve graphically):
x = -30:0.1:30;
figure(); plot(x,f(x)); grid on; grid minor;
This function has vertical asymptotes and a horizontal asymptote, at x=-3, x=1/3 and y=8/3 (finding this is left as an exercise to the reader). Let's add them to the chart and zoom to the y-vicinity of 0:
hold on; plot([-3, -3, NaN, 1/3, 1/3], 600*[-1, 1, NaN, -1, 1],'--r');
plot([-30, 30], 8/3*[1 1], '--m'); ylim([-10 10]);
There appear to be two solution, one between the vertical asymptotes and another to the right of the right asymptote. We can define these regions for fzero:
% Find zeros:
z = [ fzero(f, [-3+eps(3) 1/3-eps(1/3)] ),... First solution
fzero(f, [1/3+eps, 30])]; % Second solution
(where 30 is some sufficiently large number) and we get:
z =
0.1902 21.6848

How can I fill an area below a 3D graph in MATLAB?

I created the following 3d plot in MATLAB using the function plot3:
Now, I want to get a hatched area below the "2d sub-graphs" (i.e. below the blue and red curves). Unfortunately, I don't have any idea how to realize that.
I would appreciate it very much if somebody had an idea.
You can do this using the function fill3 and referencing this answer for the 2D case to see how you have to add points on the ends of your data vectors to "close" your filled polygons. Although creating a pattern (i.e. hatching) is difficult if not impossible, an alternative is to simply adjust the alpha transparency of the filled patch. Here's a simple example for just one patch:
x = 1:10;
y = rand(1, 10);
hFill = fill3(zeros(1, 12), x([1 1:end end]), [0 y 0], 'b', 'FaceAlpha', 0.5);
grid on
And here's the plot this makes:
You can also create multiple patches in one call to fill3. Here's an example with 4 sets of data:
nPoints = 10; % Number of data points
nPlots = 4; % Number of curves
data = rand(nPoints, nPlots); % Sample data, one curve per column
% Create data matrices:
[X, Y] = meshgrid(0:(nPlots-1), [1 1:nPoints nPoints]);
Z = [zeros(1, nPlots); data; zeros(1, nPlots)];
patchColor = [0 0.4470 0.7410]; % RGB color for patch edge and face
% Plot patches:
hFill = fill3(X, Y, Z, patchColor, 'LineWidth', 1, 'EdgeColor', patchColor, ...
'FaceAlpha', 0.5);
set(gca, 'YDir', 'reverse', 'YLim', [1 nPoints]);
grid on
And here's the plot this makes:

How to create three Y-axis in one graph? [duplicate]

I have 4 sets of values: y1, y2, y3, y4 and one set x. The y values are of different ranges, and I need to plot them as separate curves with separate sets of values on the y-axis.
To put it simple, I need 3 y-axes with different values (scales) for plotting on the same figure.
Any help appreciated, or tips on where to look.
This is a great chance to introduce you to the File Exchange. Though the organization of late has suffered from some very unfortunately interface design choices, it is still a great resource for pre-packaged solutions to common problems. Though many here have given you the gory details of how to achieve this (#prm!), I had a similar need a few years ago and found that addaxis worked very well. (It was a File Exchange pick of the week at one point!) It has inspired later, probably better mods. Here is some example output:
(source: mathworks.com)
I just searched for "plotyy" at File Exchange.
Though understanding what's going on in important, sometimes you just need to get things done, not do them yourself. Matlab Central is great for that.
One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color' properties of the top two set to 'none' so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.
Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:
%# Some sample data:
x = 0:20;
N = numel(x);
y1 = rand(1,N);
y2 = 5.*rand(1,N)+5;
y3 = 50.*rand(1,N)-50;
%# Some initial computations:
axesPosition = [110 40 200 200]; %# Axes position, in pixels
yWidth = 30; %# y axes spacing, in pixels
xLimit = [min(x) max(x)]; %# Range of x values
xOffset = -yWidth*diff(xLimit)/axesPosition(3);
%# Create the figure and axes:
figure('Units','pixels','Position',[200 200 330 260]);
h1 = axes('Units','pixels','Position',axesPosition,...
'Color','w','XColor','k','YColor','r',...
'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
'Color','none','XColor','k','YColor','m',...
'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
'Color','none','XColor','k','YColor','b',...
'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
xlabel(h1,'time');
ylabel(h3,'values');
%# Plot the data:
plot(h1,x,y1,'r');
plot(h2,x,y2,'m');
plot(h3,x,y3,'b');
and here's the resulting figure:
I know of plotyy that allows you to have two y-axes, but no "plotyyy"!
Perhaps you can normalize the y values to have the same scale (min/max normalization, zscore standardization, etc..), then you can just easily plot them using normal plot, hold sequence.
Here's an example:
%# random data
x=1:20;
y = [randn(20,1)*1 + 0 , randn(20,1)*5 + 10 , randn(20,1)*0.3 + 50];
%# plotyy
plotyy(x,y(:,1), x,y(:,3))
%# orginial
figure
subplot(221), plot(x,y(:,1), x,y(:,2), x,y(:,3))
title('original'), legend({'y1' 'y2' 'y3'})
%# normalize: (y-min)/(max-min) ==> [0,1]
yy = bsxfun(#times, bsxfun(#minus,y,min(y)), 1./range(y));
subplot(222), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('minmax')
%# standarize: (y - mean) / std ==> N(0,1)
yy = zscore(y);
subplot(223), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('zscore')
%# softmax normalization with logistic sigmoid ==> [0,1]
yy = 1 ./ ( 1 + exp( -zscore(y) ) );
subplot(224), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('softmax')
Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.
Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!
close all
clear all
display('Generating data');
x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);
display('Plotting');
figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
'YColor','b',...
'YLim',[0,1],...
'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','left',...
'Color','none',...
'XColor','k',...
'YColor','r',...
'YLim',[0,10],...
'YTick',[1, 3, 5, 7, 9],...
'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)
ax3 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','g',...
'YLim',[0,100],...
'YTick',[0, 20, 40, 60, 80, 100],...
'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)
ax4 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','c',...
'YLim',[0,100],...
'YTick',[10, 30, 50, 70, 90],...
'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)
(source: pablorodriguez.info)
PLOTYY allows two different y-axes. Or you might look into LayerPlot from the File Exchange. I guess I should ask if you've considered using HOLD or just rescaling the data and using regular old plot?
OLD, not what the OP was looking for:
SUBPLOT allows you to break a figure window into multiple axes. Then if you want to have only one x-axis showing, or some other customization, you can manipulate each axis independently.
In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:
clear
clc
x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];
xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;
for i=1:N_
L=1-(numberOfExtraPlots*a)-0.2;
axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
if(i==1)
color = [rand(1),rand(1),rand(1)];
figure('Units','pixels','Position',[200 200 1200 600])
axes('Units','normalized','Position',axesPosition,...
'Color','w','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'NextPlot','add');
plot(x,Y(i,:),'Color',color);
xlabel('Time (s)');
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
else
color = [rand(1),rand(1),rand(1)];
axes('Units','normalized','Position',axesPosition,...
'Color','none','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
V = (xWidth*a*(i-1))/L;
b=xLimit+[V 0];
x_=linspace(b(1),b(2),10);
plot(x_,Y(i,:),'Color',color);
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
end
end
The code above will produce something like this:

How to plot a intersection operation on two vectors MatLab

I'm trying to represent a the intersection of two fuzzy sets as a 3d mesh in MatLab.
Here are my sets of vectors:
x = [0.3 0.5 0.7]
y = [0.5 0.7 0.1]
Followed by these statements:
[u,v] = meshgrid(x,y)
w = min(u,v)
mesh(u,v,w)
The x and y ticks seem to be all over the place and do not correlate to the actual index number of each vector i.e. 1 to 3, and the graph should represent the shape of a small triangle/T-norm.
At the moment it looks like this:
Here is an example out of my book I'm following:
Ignore what looks like fractions, they are delimiters. Here is the resulting graph:
After looking up fuzzy sets and intersections, here's what I've come up with. First, let's reproduce the textbook example:
% possible values and associated degrees of truth for F
Fv = 1 : 5;
Ft = [0 0.5 1 0.5 0];
% possible values and associated degrees of truth for D
Dv = 2 : 4;
Dt = [0 1 0];
% determine degrees of truth for fuzzy intersection
It = bsxfun(#min, Ft', Dt);
% plot
h = mesh(Dv, Fv, It);
set(h, 'FaceColor', 'none')
set(h, 'EdgeColor', 'k')
xlim([0 4.5])
ylim([0 5])
xlabel D
ylabel F
view(37.5, 30)
The result is:
Not as pretty as in your book, but the same thing.
Applying the same code to your example yields:
Via the arguments u,v you are telling mesh to use the values in them, i.e. the values from x and y, for the positioning of the data points and corresponding ticks. If you just want positions and ticks at 1, 2, 3, leave these arguments out.
mesh(w)

Emulate ggplot2 default color palette in MATLAB

I was wondering if anyone knew how to emulate the ggplot2 default color palette in MATLAB? i.e the one given by scale_color_hue() in ggplot2.
Or equivalently, does anyone know how to pick evenly spaced colors around the HCL color wheel in Matlab?
Some code would be nice. Thank you very much!
Here's a function to get equidistant hsv colours, which is more or less the default scale_colour_hue in ggplot2 for discrete values,
%Color scale in hsv
%
%colorscale(n)
%colorscale(n, 'hue', [min max])
%colorscale(n, 'saturation', saturation)
%colorscale(n, 'value', value)
%
%Input: n
%Optional: hue in [0 1]x[0 1] range (default [0.1 0.9]),
% saturation [0 1] (default 0.5), value in [0 1] (default 0.8)
%
%Output: nx3 rgb matrix
%
%Examples:
% n = 10;
% cols = colorscale(n, 'hue', [0.1 0.8], 'saturation' , 1, 'value', 0.5);
%
%for aa = 1:10;
% plot(1:10, (1:10) + aa, 'Color', cols(aa,:), 'Linewidth',2)
% hold on
%end;
%
% % plot a matrix
% v = transpose(1:10);
% set(gca, 'ColorOrder', colorscale(5));
% set(gca,'NextPlot','replacechildren')
% plot(v, [v, v+1, v+2, v+ 3, v+4, v+5]) ;
%
function cols = colorscale(n, varargin)
p = inputParser;
p.addRequired('n', #isnumeric);
p.addOptional('hue', [0.1 0.9], #(x) length(x) == 2 & min(x) >=0 & max(x) <= 1);
p.addOptional('saturation', 0.5, #(x) length(x) == 1);
p.addOptional('value', 0.8, #(x) length(x) == 1);
p.parse(n, varargin{:});
cols = hsv2rgb([transpose(linspace(p.Results.hue(1), p.Results.hue(2), p.Results.n)), ...
repmat(p.Results.saturation, p.Results.n, 1), repmat(p.Results.value, n,1) ]);
I created a ggplot2-like plotting library for Matlab called gramm, which reproduces many of ggplot2 functionalities, including its Hue-Chroma-Lightness color palette. It's on gitHub/gramm and fileexchange/gramm. You can look inside for how HCL colormaps are created (This part of gramm uses code from the PandA – Perception and Action – toolbox).
I think in general ggplot2 relies heavily on the Brewer Colour Palettes, which should thus have pallettes like the one you are looking for. So maybe just go to the above link and get the RGB values of any set you like (and cite accordingly).
And Matlab should have some way of specifying RGB colours, I'm sure (although I have no clue how to do that - maybe worth a new question on its own?).