Gaussian mixture model - get the contour of given probability value : Matlab - matlab

I need to identify the 99% probability contour of a GMM fitted to data. Following this example, I'd like to be able to specify which contours to plot, and the x,y, of them.
mu1 = [1 2]; Sigma1 = [2 0; 0 0.5];
mu2 = [-3 -5]; Sigma2 = [1 0;0 1];
X = [mvnrnd(mu1,Sigma1,1000); mvnrnd(mu2,Sigma2,1000)];
GMModel = fitgmdist(X,2);
figure
y = [zeros(1000,1);ones(1000,1)];
h = gscatter(X(:,1),X(:,2),y);
hold on
gmPDF = #(x,y) arrayfun(#(x0,y0) pdf(GMModel,[x0 y0]),x,y);
g = gca;
fcontour(gmPDF,[g.XLim g.YLim])
title('{\bf Scatter Plot and Fitted Gaussian Mixture Contours}')
legend(h,'Model 0','Model1')
hold off
So, in the following figure, I'd like to to be able to plot the 99% in dashed black line "k". Any idea how to accomplish this?

You can display and get the coordinates of the given contour line specifying the LevelList property of fcontour, and then reading the ContourMatrix property of the contour handle:
% Random function, insert here yours
f = #(x,y) arrayfun(#(x0,y0) x0.^2 + y0.^2 - 0.1,x,y);
% The function value you want to get the contour for
lvl = 0.99;
% Plot the contour line
cHandle = fcontour(f, '--k', 'LevelList', [lvl]);
hold on
% Get the coordinates
lvlX = cHandle.ContourMatrix(1, 2:end);
lvlY = cHandle.ContourMatrix(2, 2:end);
% For a check:
plot(lvlX, lvlY, '--r')

Related

coloring 3D plots on MATLAB

I made two 3D plots on the same axis. now I desire to give them different colors for easy identification. How do I do this coloring? The MATLAB code is shown below.
tic
Nx = 50;
Ny = 50;
x = linspace(0,1,Nx);
y = linspace(0,0.5,Ny);
[X,Y] = meshgrid(x,y);
[M,N] = size(X);
for m=1:M
for n=1:N
%get x,y coordinate
x_mn = X(m,n);
y_mn = Y(m,n);
%%% X=D2 and Y=D1
%Check if x_mn and y_mn satisfy requirement
if(x_mn >= y_mn)
%evaluate function 1
Z(m,n) = (x_mn^2 - 2*x_mn*y_mn + y_mn^2);
Z_1(m,n) = (x_mn^2);
elseif(x_mn < y_mn)
%evaluate function 2
Z(m,n) = 0;
Z_1(m,n) = (x_mn^2);
%% Z(m,n) = 2*(2*x_mn*y_mn + y_mn - y_mn^2 - 2*x_mn);
else
Z(m,n) = 0;
end
end
end
%Plot the surface
figure
surf(X,Y,Z) %first plot
surfc(X,Y,Z)
hold on
surf(X,Y,Z_1) %second plot
xlabel('Dm');
ylabel('D');
zlabel('pR');
grid on
shading interp
toc
disp('DONE!')
How can I create two differently colored surfaces?
figure
surf(X,Y,Z) %first plot
surfc(X,Y,Z)
hold on
surf(X,Y,Z_1)
Your surfc() call actually overwrites your surf() call, is this intended?
As to your colour: the documentation is a marvellous thing:
surfc(X,Y,Z,C) additionally specifies the surface color.
In other words: just specify the colour as you want it. C needs to be a matrix of size(Z) with the desired colours, i.e. set all of them equal to create an monocoloured surface:
x = 1:100;
y = 1:100;
z = rand(100);
figure;
surfc(x,y,z,ones(size(z)))
hold on
surfc(x,y,z+6,ones(size(z))+4)
Results in (MATLAB R2007b, but the syntax is the same nowadays)

Adding two color maps using imagesc between two sets of curves with specified boundaries (MATLAB)

I'm trying to add two color gradients between two curves (in this example these are lines).
This is the code for what I've done so far
% the mesh
ns=1000;
t_vec = linspace(0,100,ns);
x_vec = linspace(-120,120,ns);
[N, X] = meshgrid(t_vec, x_vec);
% the curves
x1 = linspace(0,100,ns); x2 = linspace(10,110,ns);
y1 = linspace(-50,50,ns); y2 = linspace(-20,80,ns);
X1 = repmat(x1, [size(N, 1) 1]); X2 = repmat(x2, [size(N, 1) 1]);
Y1 = repmat(y1, [size(N, 1) 1]); Y2 = repmat(y2, [size(N, 1) 1]);
% the gradient function
cc = #(x,x2,x1) ...
1./(1+(exp(-x)./(exp(-x1)-exp(-x2))));
for i=1:ns
CData1(:,i)=cc(x_vec,x2(i),x1(i));
CData2(:,i)=cc(x_vec,y2(i),y1(i));
end
CData=CData1+CData2; % here I've added the two gradients
% mask
mask = true(size(N));
mask((X > Y2 | X < Y1) & (X > X2 | X < X1)) = false;
% finalized data
Z = NaN(size(N));
Z(mask) = CData(mask);
Z = normalize(Z, 1, 'range');
% draw a figure!
figure(1); clf;
ax = axes; % create some axes
sc = imagesc(ax, t_vec, x_vec, Z); % plot the data
colormap('summer')
ax.YDir = 'normal' % set the YDir to normal again, imagesc reverses it by default;
hold on
plot(t_vec,x1,'r',t_vec,x2,'r',t_vec,y1,'k',t_vec,y2,'k')
ylim([-120 120]); xlim([0 100])
the result I get is
As you can see, the gradient stretches between the most lower line to the most upper line.
How can I separate between the two color data and present them in the same image (using imagesc) using a different colormap?
Here is a function called comat (see at the bottom of the answer) that I once made for something similar, I think you might find it useful in your case. Here's an example how to use it:
imagesc(t_vec, x_vec, comat(CData2.*mask,CData1.*mask));
colormap([summer(256).^2;flipud(bone(256).^0.5)]); % and the two colormaps
set(gca,'Ydir','normal')
The result is:
I'm not sure this is what you meant, but you can see how the data of the thin stripe is only visualized using the bone b&w colormap, while the rest is with summer. I also "abused" the colormaps with a ^ factor for emphasizing the range of the gradient.
function z = comat(z1,z2,DR)
% the function combines matrices z1 and z2 for the purpose of
% visualization with 2 different colormaps
% z1,z2 - matrices of the same size
% DR - the dynamic range for visualization (default 256)
%example
%imagesc(comat(z1,z2)); colormap([jet(256);bone(256)]);
%defaults
if (nargin < 3); DR=256; end
%normalize to dynamic range, integer values in the range 0 to DR
z1=double(uint32(DR*(z1-min(z1(:)))./(max(z1(:)-min(z1(:))))));
z2=double(uint32(DR*(z2-min(z2(:)))./(max(z2(:)-min(z2(:))))+DR+1));
thr=DR+2+10; %threshold where data is not important for z2, must be at least DR+2
z=z1.*(z2<thr)+z2.*(z2>thr);
end

Matlab: patch area between two curves which depend on the curves values

I'm trying to fill an area between two curves with respect to a function which depends on the values of the curves.
Here is the code of what I've managed to do so far
i=50;
cc = #(xx,x,y) 1./(1+(exp(-xx)/(exp(-x)-exp(-y))));
n_vec = 2:0.1:10;
x_vec = linspace(2,10,length(n_vec));
y_vec = abs(sin(n_vec));
N=[n_vec,fliplr(n_vec)];
X=[x_vec,fliplr(y_vec)];
figure(1)
subplot(2,1,1)
hold on
plot(n_vec,x_vec,n_vec,y_vec)
hp = patch(N,X,'b')
plot([n_vec(i) n_vec(i)],[x_vec(i),y_vec(i)],'linewidth',5)
xlabel('n'); ylabel('x')
subplot(2,1,2)
xx = linspace(y_vec(i),x_vec(i),100);
plot(xx,cc(xx,y_vec(i),x_vec(i)))
xlabel('x'); ylabel('c(x)')
This code produces the following graph
The color code which I've added represent the color coding that each line (along the y axis at a point on the x axis) from the area between the two curves should be.
Overall, the entire area should be filled with a gradient color which depends on the values of the curves.
I've assisted the following previous questions but could not resolve a solution
MATLAB fill area between lines
Patch circle by a color gradient
Filling between two curves, according to a colormap given by a function MATLAB
NOTE: there is no importance to the functional form of the curves, I would prefer an answer which refers to two general arrays which consist the curves.
The surf plot method
The same as the scatter plot method, i.e. generate a point grid.
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px = linspace(min(n_vec), max(n_vec), resolution(1));
py = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px, py);
Generate a logical array indicating whether the points are inside the polygon, but no need to extract the points:
in = inpolygon(px, py, N, X);
Generate Z. The value of Z indicates the color to use for the surface plot. Hence, it is generated using the your function cc.
pz = 1./(1+(exp(-py_)/(exp(-y_vec(i))-exp(-x_vec(i)))));
pz = repmat(pz',1,resolution(2));
Set Z values for points outside the area of interest to NaN so MATLAB won't plot them.
pz(~in) = nan;
Generate a bounded colourmap (delete if you want to use full colour range)
% generate colormap
c = jet(100);
[s,l] = bounds(pz,'all');
s = round(s*100);
l = round(l*100);
if s ~= 0
c(1:s,:) = [];
end
if l ~= 100
c(l:100,:) = [];
end
Finally, plot.
figure;
colormap(jet)
surf(px,py,pz,'edgecolor','none');
view(2) % x-y view
Feel free to turn the image arround to see how it looks like in the Z-dimention - beautiful :)
Full code to test:
i=50;
cc = #(xx,x,y) 1./(1+(exp(-xx)/(exp(-x)-exp(-y))));
n_vec = 2:0.1:10;
x_vec = linspace(2,10,length(n_vec));
y_vec = abs(sin(n_vec));
% generate grid
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px_ = linspace(min(n_vec), max(n_vec), resolution(1));
py_ = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px_, py_);
% extract points
in = inpolygon(px, py, N, X);
% generate z
pz = 1./(1+(exp(-py_)/(exp(-y_vec(i))-exp(-x_vec(i)))));
pz = repmat(pz',1,resolution(2));
pz(~in) = nan;
% generate colormap
c = jet(100);
[s,l] = bounds(pz,'all');
s = round(s*100);
l = round(l*100);
if s ~= 0
c(1:s,:) = [];
end
if l ~= 100
c(l:100,:) = [];
end
% plot
figure;
colormap(c)
surf(px,py,pz,'edgecolor','none');
view(2)
You can use imagesc and meshgrids. See comments in the code to understand what's going on.
Downsample your data
% your initial upper and lower boundaries
n_vec_long = linspace(2,10,1000000);
f_ub_vec_long = linspace(2, 10, length(n_vec_long));
f_lb_vec_long = abs(sin(n_vec_long));
% downsample
n_vec = linspace(n_vec_long(1), n_vec_long(end), 1000); % for example, only 1000 points
% get upper and lower boundary values for n_vec
f_ub_vec = interp1(n_vec_long, f_ub_vec_long, n_vec);
f_lb_vec = interp1(n_vec_long, f_lb_vec_long, n_vec);
% x_vec for the color function
x_vec = 0:0.01:10;
Plot the data
% create a 2D matrix with N and X position
[N, X] = meshgrid(n_vec, x_vec);
% evaluate the upper and lower boundary functions at n_vec
% can be any function at n you want (not tested for crossing boundaries though...)
f_ub_vec = linspace(2, 10, length(n_vec));
f_lb_vec = abs(sin(n_vec));
% make these row vectors into matrices, to create a boolean mask
F_UB = repmat(f_ub_vec, [size(N, 1) 1]);
F_LB = repmat(f_lb_vec, [size(N, 1) 1]);
% create a mask based on the upper and lower boundary functions
mask = true(size(N));
mask(X > F_UB | X < F_LB) = false;
% create data matrix
Z = NaN(size(N));
% create function that evaluates the color profile for each defined value
% in the vectors with the lower and upper bounds
zc = #(X, ub, lb) 1 ./ (1 + (exp(-X) ./ (exp(-ub) - exp(-lb))));
CData = zc(X, f_lb_vec, f_ub_vec); % create the c(x) at all X
% put the CData in Z, but only between the lower and upper bound.
Z(mask) = CData(mask);
% normalize Z along 1st dim
Z = normalize(Z, 1, 'range'); % get all values between 0 and 1 for colorbar
% draw a figure!
figure(1); clf;
ax = axes; % create some axes
sc = imagesc(ax, n_vec, x_vec, Z); % plot the data
ax.YDir = 'normal' % set the YDir to normal again, imagesc reverses it by default;
xlabel('n')
ylabel('x')
This already looks kinda like what you want, but let's get rid of the blue area outside the boundaries. This can be done by creating an 'alpha mask', i.e. set the alpha value for all pixels outside the previously defined mask to 0:
figure(2); clf;
ax = axes; % create some axes
hold on;
sc = imagesc(ax, n_vec, x_vec, Z); % plot the data
ax.YDir = 'normal' % set the YDir to normal again, imagesc reverses it by default;
% set a colormap
colormap(flip(hsv(100)))
% set alpha for points outside mask
Calpha = ones(size(N));
Calpha(~mask) = 0;
sc.AlphaData = Calpha;
% plot the other lines
plot(n_vec, f_ub_vec, 'k', n_vec, f_lb_vec, 'k' ,'linewidth', 1)
% set axis limits
xlim([min(n_vec), max(n_vec)])
ylim([min(x_vec), max(x_vec)])
there is no importance to the functional form of the curves, I would prefer an answer which refers to two general arrays which consist the curves.
It is difficult to achieve this using patch.
However, you may use scatter plots to "fill" the area with coloured dots. Alternatively, and probably better, use surf plot and generate z coordinates using your cc function (See my seperate solution).
The scatter plot method
First, make a grid of points (resolution 500*500) inside the rectangular space bounding the two curves.
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px = linspace(min(n_vec), max(n_vec), resolution(1));
py = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px, py);
figure;
scatter(px(:), py(:), 1, 'r');
The not-interesting figure of the point grid:
Next, extract the points inside the polygon defined by the two curves.
in = inpolygon(px, py, N, X);
px = px(in);
py = py(in);
hold on;
scatter(px, py, 1, 'k');
Black points are inside the area:
Finally, create color and plot the nice looking gradient colour figure.
% create color for the points
cid = 1./(1+(exp(-py)/(exp(-y_vec(i))-exp(-x_vec(i)))));
c = jet(101);
c = c(round(cid*100)+1,:); % +1 to avoid zero indexing
% plot
figure;
scatter(px,py,16,c,'filled','s'); % use size 16, filled square markers.
Note that you may need a fairly dense grid of points to make sure the white background won't show up. You may also change the point size to a bigger value (won't impact performance).
Of cause, you may use patch to replace scatter but you will need to work out the vertices and face ids, then you may patch each faces separately with patch('Faces',F,'Vertices',V). Using patch this way may impact performance.
Complete code to test:
i=50;
cc = #(xx,x,y) 1./(1+(exp(-xx)/(exp(-x)-exp(-y))));
n_vec = 2:0.1:10;
x_vec = linspace(2,10,length(n_vec));
y_vec = abs(sin(n_vec));
% generate point grid
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px_ = linspace(min(n_vec), max(n_vec), resolution(1));
py_ = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px_, py_);
% extract points
in = inpolygon(px, py, N, X);
px = px(in);
py = py(in);
% generate color
cid = 1./(1+(exp(-py)/(exp(-y_vec(i))-exp(-x_vec(i)))));
c = jet(101);
c = c(round(cid*100)+1,:); % +1 to avoid zero indexing
% plot
figure;
scatter(px,py,16,c,'filled','s');

How to superimpose two contour maps onto each other in matlab?

I have two contour maps in Matlab and each of the two maps has a single curve specifying a single Z-value. I want to super impose the two contour maps so that I can find the single solution where the two z-value curves intersect. How could I go about super imposing the two contour maps?
% the two contour maps are coded the exact same way, but with different z-values
x = 0.05:0.05:1;
y = 0.0:0.05:1;
[X, Y] = meshgrid(x, y);
% Z-value data is copied from excel and pasted into an array
Z = [data]
contourf(X, Y, Z);
pcolor(X, Y, Z); hold on
shading interp
title();
xlabel();
ylabel();
colorbar
val = %z-value to plot onto colormap
tol = %tolerance
idxZval = (Z <= val+tol) & (Z >= val-tol);
plot(X(idxZval), Y(idxZval))[enter image description here][1]
The end result you seek is possible using contourc or using contour specifying the same contours (isolines).
This answer extends this answer in Approach 1 using contourc and provides a simple solution with contour in Approach 2.
You might ask "Why Approach 1 when Approach 2 is so simple?"
Approach 1 provides a way to directly access the individual isolines in the event you require a numerical approach to searching for intersections.
Approach 1
Example Data:
% MATLAB R2018b
x = 0:0.01:1;
y = 0:0.01:1;
[X,Y] = meshgrid(x,y);
Z = sqrt(X.^3+Y); % Placeholder 1
W = sqrt(X.*Y + X.^2 + Y.^(2/3)); % Placeholder 2
Overlay Single Isoline from 2 Contour Plots
Mimicking this answer and using
v = [.5 0.75 .85 1]; % Values of Z to plot isolines
we can visualize these two functions, Z, and W, respectively.
We can overlay the isolines since they share the same (x,y) domain. For example, they both equal 0.8 as displayed below.
val = 0.8; % Isoline value to plot (for Z & W)
Ck = contourc(x,y,Z,[val val]);
Ck2 = contourc(x,y,W,[val val]);
figure, hold on, box on
plot(Ck(1,2:end),Ck(2,2:end),'k-','LineWidth',2,'DisplayName',['Z = ' num2str(val)])
plot(Ck2(1,2:end),Ck2(2,2:end),'b-','LineWidth',2,'DisplayName',['W = ' num2str(val)])
legend('show')
Overlay Multiple Isolines from 2 Contour Plots
We can also do this for more isolines at a time.
v = [1 0.5]; % Isoline values to plot (for Z & W)
figure, hold on, box on
for k = 1:length(v)
Ck = contourc(x,y,Z,[v(k) v(k)]);
Ck2 = contourc(x,y,W,[v(k) v(k)]);
p(k) = plot(Ck(1,2:end),Ck(2,2:end),'k-','LineWidth',2,'DisplayName',['Z = ' num2str(v(k))]);
p2(k) = plot(Ck2(1,2:end),Ck2(2,2:end),'b-','LineWidth',2,'DisplayName',['W = ' num2str(v(k))]);
end
p(2).LineStyle = '--';
p2(2).LineStyle = '--';
legend('show')
Approach 2
Without making it pretty...
% Single Isoline
val = 1.2;
contour(X,Y,Z,val), hold on
contour(X,Y,W,val)
% Multiple Isolines
v = [.5 0.75 .85 1];
contour(X,Y,Z,v), hold on
contour(X,Y,W,v)
It is straightforward to clean these up for presentation. If val is a scalar (single number), then c1 = contour(X,Y,Z,val); and c2 = contour(X,Y,W,val) gives access to the isoline for each contour plot.

Applying 3D rotation matrix to x, y, z values obtained from surface function

Applying 3D rotation matrix to the x,y,z values obtained from surface function object. The error I get is due to the matrix not being nonconforment but how can I adjust the matrix correctly?
I know hgtransform / makehgtform can do rotations but I need to use rotation matrices since I plan on testing it using matrices created from quaternions.
I've created a little plane out of cylinders and the surface functions.
See code below:
clear all,clf
ax=axes('XLim',[-2 2],'YLim', [-2 10],'ZLim',[-1.5 1.5]);
grid on;
%axis equal;
xlabel('x');
ylabel('y');
zlabel('z');
ax
% rotate around
rot_mat = [.707 -.707 0;.707 .707 0; 0 0 1] %rotation matrix
[xc yc zc] = cylinder([0.1 0.0]); %cone
[x y z]= cylinder([0.2 0.2]);
h(1) = surface(xc,zc,-yc,'FaceColor', 'red'); %noise cone
h(2) = surface(z,y,0.5*x,'FaceColor', 'blue'); %right wing
h(3) = surface(-z,y,0.5*x,'FaceColor', 'yellow');%left wing
h(4) = surface(x,-1.5*z,0.5*y,'FaceColor', 'green'); %main body
h(5) = surface(xc,(1.5*yc)-1.3,z*.5,'FaceColor', 'red'); %tail
view(3);
x_temp = get(h(1),'xdata'); % get x values
y_temp = get(h(1),'ydata');
z_temp =get(h(1),'zdata');
xc_new=x_temp.*rot_mat;
%zc_new=
%yc_new=
I can get the x,y, and z value by using the commands
x_temp = get(h(1),'xdata');
y_temp = get(h(1),'ydata');
z_temp = get(h(1),'zdata');
The error I get is due to the matrix being nonconforment but how can I adjust the matrix correctly?
error: test_object_matrix_rot: product: nonconformant arguments (op1 is 2x21, op2 is 3x3).
The error is with the line xc_new=x_temp.*rot_mat;
PS: I'm using Octave 5.0.91 which is like Matlab
YOu are messing up a lot of things......in fact I would say, you have made your work complex. YOu should straight away work on matrices to rotate to new positons instead of arrays and picking them from the figure.
This line:
x_temp = get(h(1),'xdata'); % get x values
giving you a 2*21 array and your rot_mat is 3X3.....you cannot multiply them. YOu need to pick (x,y,z) and multiply this point with rotation matrix to get the point shifted. Check the below pseudo code.....yo can develop your logic with the below example code.
t = 0:0.1:1;
[X,Y,Z] = cylinder((t));
%% Rotation
th = pi/2 ;
Rx = [1 0 0 ; 0 cos(th) -sin(th) ; 0 sin(th) cos(th)] ;
P0 = [X(:) Y(:) Z(:)] ;
P1 = P0*Rx ;
X1 = reshape(P1(:,1),size(X)) ;
Y1 = reshape(P1(:,2),size(X)) ;
Z1 = reshape(P1(:,3),size(X)) ;
figure
hold on
surf(X,Y,Z)
surf(X1,Y1,Z1)
view(3)