Problem with normalizing a function with likelihood - matlab

I have a problem with the following code. In the evidence part, the value is very small so, in the end, the probabilities are not calculated. I need to normalize it, but in which part should it be?
The code in MATLAB is:
clear all; close all; clc;
randn('seed', 1234);
resistivities = [50 200 2000 1500];
thicknesses = [500 100 200];
Par_real = [resistivities, thicknesses];
dataFreq = logspace(log10(0.001), log10(1000), 100);
[Ydata, phase] = modelMT2(Par_real, dataFreq);
sigma = 0.1;
Yexp = Ydata + sigma*randn(size(Ydata));
plot(dataFreq, Yexp, '.'); hold on; plot(dataFreq, Ydata, '-')
nsamples = 20000;
R1 = 5;
R2 = 2050;
P1 = 25;
P2 = 500;
Resis = R1 + (R2-R1)*rand(nsamples, 7);
Profs = P1 + (P2-P1)*rand(nsamples, 6);
for ii=1:nsamples
par3C = [Resis(ii, 1:3), Profs(ii, 1:2)];
par4C = [Resis(ii, 1:4), Profs(ii, 1:3)];
par5C = [Resis(ii, 1:5), Profs(ii, 1:4)];
par7C = [Resis(ii, 1:7), Profs(ii, 1:6)];
Like_M3C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par3C);
Like_M4C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par4C);
Like_M5C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par5C);
Like_M7C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par7C);
end
figure()
subplot(1, 2, 1)
plot(exp(Like_M5C))
subplot(1, 2, 2)
hist(exp(Like_M5C))
Evidencia(1) = mean(exp(Like_M3C));
Evidencia(2) = mean(exp(Like_M4C));
Evidencia(3) = mean(exp(Like_M5C));
Evidencia(4) = mean(exp(Like_M7C));
Denominador = sum(Evidencia);
PPMM = Evidencia/Denominador;
fprintf('La probabilidad de los modelos : \n');
fprintf('--------------------------------\n');
fprintf('Modelo M3C: %.4f \n', PPMM(1));
fprintf('Modelo M4C: %.4f \n', PPMM(2));
fprintf('Modelo M5C: %.4f \n', PPMM(3));
fprintf('Modelo M7C: %.4f \n', PPMM(4));
figure()
model = [1, 2, 3, 4];
bar(model, PPMM), grid on
ylim([0, 1])
xlabel('Modelo')
ylabel('Probabilidad del modelo')
function [LogPDF_post] = log_likelihood(Mod, xx, data, sigma, oldpar)
erro = (Mod(oldpar, xx) - data)';
LogPDF_post = -0.5 * erro' * 1/sigma^2 * erro;
end
I have tried to normalize the likelihood as follows, but it doesn't work. It gives equal probability in all cases.
function [LogPDF_norma] = log_likelihood(Mod, xx, data, sigma, oldpar)
erro = (Mod(oldpar, xx) - data)';
LogPDF_post = -0.5 * erro' * 1/sigma^2 * erro;
LogPDF_norma = (1/max(LogPDF_post))*LogPDF_post;
end

Related

Making colorbar tick labels a string above and below bar, remove ticks - Matlab

I am trying to reproduce the colorbar below for my chart. Specifically it is the string colorbar axis title (above and below the colorbar) that I am struggling with, the rest seems fine.
Below is my current code:
time_begin = [1981, 1, 1, 0,0,0];
time_end = [2010,12,31,23,0,0];
years = (time_begin(1):time_end(1))';
nyears = length(years);
TXx1 = randi(100, 288, 192, 30);
lat = rand(192, 1);
lon = rand(288, 1);
time = rand(30,1);
M = numel(lon);
N = numel(lat);
slope1 = zeros(M, N);
intercept1 = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
for i = 1 : M
for j = 1 : N
y1 = squeeze(TXx1(i, j, :));
c = regress(y1, x);
intercept1(i, j) = c(1);
slope1(i, j) = c(2);
end
end
TXx2 = randi(100, 288, 192, 30);
slope2 = zeros(M, N);
intercept2 = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
for i = 1 : M
for j = 1 : N
y2 = squeeze(TXx2(i, j, :));
c = regress(y2, x);
intercept2(i, j) = c(1);
slope2(i, j) = c(2);
end
end
figure()
set(gcf, 'color', 'w');
temp = [slope1(:) slope2(:)];
temp(temp == 0) = NaN;
[Q,Qc] = hist3(temp,'Nbins',[100 100],'CDataMode','auto');
Qx = cell2mat(Qc(1));
Qy = cell2mat(Qc(2));
Q = Q';
Q = Q./trapz(Qy,trapz(Qx,Q,2));
surf(Qx,Qy,Q,'FaceColor','interp','EdgeColor','none')
grid off
set(gca, 'Fontsize', 12, 'Fontweight', 'Bold'); %added
cmap = jet(500);
cmap(1,:) = [1,1,1];
colormap(cmap);
h=colorbar;
set(h,'position',[.91 .34 .031 .475]) %[xposition yposition width height].
set(get(h,'ylabel'),'string','Point density');
set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',});
view(0,90)
Here is my current colourbar:
Replace this line:
set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',});
with:
h.YTick = h.Limits;
h.YTickLabel = {'Low', 'High'};
This makes two tick-lines and two tick labels. By setting YTicks of the colorbar to its limits, the tick-lines get overlapped by colorbar boundary. So these get hidden and now there is no need to remove them.
However there is this TickLength property which can be used otherwise i.e.
h.TickLength = 0;
Result:

Plot equally spaced markers along a spiral

I want to move a red star marker along the spiral trajectory with an equal distance of 5 units between the red star points on its circumference like in the below image.
vertspacing = 10;
horzspacing = 10;
thetamax = 10*pi;
% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/2/pi;
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta)+50;
y = b*theta.*sin(theta)+50;
% Calculation of equidistant (xi,yi) points on spiral.
smax = 0.5*b*thetamax.*thetamax;
s = 0:horzspacing:smax;
thetai = sqrt(2*s/b);
xi = b*thetai.*cos(thetai);
yi = b*thetai.*sin(thetai);
plot(x,y,'b-');
hold on
I want to get a figure that looks like the following:
This is my code for the circle trajectory:
% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3= 20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on
% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
plot(x1(i),y1(i),'r*')
pause(0.1)
end
for i = 1 : length(theta2)
plot(x2(i),y2(i),'r*')
pause(0.1)
end
for i = 1 : length(theta3)
plot(x3(i),y3(i),'r*')
pause(0.1)
end
I can't think of a way to compute distance along a spiral, so I'm approximating it with circles, in hopes that it will still be useful.
My solution relies on the InterX function from FEX, to find the intersection of circles with the spiral. I am providing an animation so it is easier to understand.
The code (tested on R2017a):
function [x,y,xi,yi] = q44916610(doPlot)
%% Input handling:
if nargin < 1 || isempty(doPlot)
doPlot = false;
end
%% Initialization:
origin = [50,50];
vertspacing = 10;
thetamax = 5*(2*pi);
%% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/(2*pi);
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta) + origin(1);
y = b*theta.*sin(theta) + origin(2);
%% Calculation of equidistant (xi,yi) points on spiral.
DST = 5; cRes = 360;
numPts = ceil(vertspacing*thetamax); % Preallocation
[xi,yi] = deal(NaN(numPts,1));
if doPlot && isHG2() % Plots are only enabled if the MATLAB version is new enough.
figure(); plot(x,y,'b-'); hold on; axis equal; grid on; grid minor;
hAx = gca; hAx.XLim = [-5 105]; hAx.YLim = [-5 105];
hP = plot(xi,yi,'r*');
else
hP = struct('XData',xi,'YData',yi);
end
hP.XData(1) = origin(1); hP.YData(1) = origin(2);
for ind = 2:numPts
P = InterX([x;y], makeCircle([hP.XData(ind-1),hP.YData(ind-1)],DST/2,cRes));
[~,I] = max(abs(P(1,:)-origin(1)+1i*(P(2,:)-origin(2))));
if doPlot, pause(0.1); end
hP.XData(ind) = P(1,I); hP.YData(ind) = P(2,I);
if doPlot, pause(0.1); delete(hAx.Children(1)); end
end
xi = hP.XData(~isnan(hP.XData)); yi = hP.YData(~isnan(hP.YData));
%% Nested function(s):
function [XY] = makeCircle(cnt, R, nPts)
P = (cnt(1)+1i*cnt(2))+R*exp(linspace(0,1,nPts)*pi*2i);
if doPlot, plot(P,'Color',lines(1)); end
XY = [real(P); imag(P)];
end
end
%% Local function(s):
function tf = isHG2()
try
tf = ~verLessThan('MATLAB', '8.4');
catch
tf = false;
end
end
function P = InterX(L1,varargin)
% DOCUMENTATION REMOVED. For a full version go to:
% https://www.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections
narginchk(1,2);
if nargin == 1
L2 = L1; hF = #lt; %...Avoid the inclusion of common points
else
L2 = varargin{1}; hF = #le;
end
%...Preliminary stuff
x1 = L1(1,:)'; x2 = L2(1,:);
y1 = L1(2,:)'; y2 = L2(2,:);
dx1 = diff(x1); dy1 = diff(y1);
dx2 = diff(x2); dy2 = diff(y2);
%...Determine 'signed distances'
S1 = dx1.*y1(1:end-1) - dy1.*x1(1:end-1);
S2 = dx2.*y2(1:end-1) - dy2.*x2(1:end-1);
C1 = feval(hF,D(bsxfun(#times,dx1,y2)-bsxfun(#times,dy1,x2),S1),0);
C2 = feval(hF,D((bsxfun(#times,y1,dx2)-bsxfun(#times,x1,dy2))',S2'),0)';
%...Obtain the segments where an intersection is expected
[i,j] = find(C1 & C2);
if isempty(i), P = zeros(2,0); return; end
%...Transpose and prepare for output
i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
L = dy2(j).*dx1(i) - dy1(i).*dx2(j);
i = i(L~=0); j=j(L~=0); L=L(L~=0); %...Avoid divisions by 0
%...Solve system of eqs to get the common points
P = unique([dx2(j).*S1(i) - dx1(i).*S2(j), ...
dy2(j).*S1(i) - dy1(i).*S2(j)]./[L L],'rows')';
function u = D(x,y)
u = bsxfun(#minus,x(:,1:end-1),y).*bsxfun(#minus,x(:,2:end),y);
end
end
Result:
Note that in the animation above, the diameter of the circle (and hence the distance between the red points) is 10 and not 5.

Solving Boundary Value with bvp4c Matlab

i'm trying to solve a boundary value problem of an system q' = f(q(t), a(t)) with an input a using bvp4c in Matlab. Where q = [q1, q2, q1_dot, q2_dot]'
My Matlab Code does not work properly. Does anyone know how to solve this?
img: System Equation of the One Pendulum
a is a input function.
the initial state: q1(0) = pi, q2(0) = 0, q1_dot(0) = 0, q2_dot(0) = 0.
the end state: q1(te) = 0, q2(te) = 0, q1_dot(te) = 0, q2_dot(te) = 0.
input initial state: a(0) = 0, and the end state: a(te) = 0.
i've in total 10 boundaries. one_pendulum_bc can take only 5 and not more and fewer.
function one_pendulum
options = []; % place holder
solinit = bvpinit(linspace(0,1,1000),[pi, 0, 0, 0],0);
sol = bvp4c(#one_pendulum_ode,#one_pendulum_bc,solinit,options);
t = sol.x;
plot(t, sol.y(1,:))
figure(2)
plot(t, sol.y(2,:))
figure(3)
plot(t, sol.y(3,:))
figure(4)
plot(t, sol.y(4,:))
% --------------------------------------------------------------------------
function dydx = one_pendulum_ode(x,y,a)
% Parameter of the One-Pendulum
m1 = 0.3583; % weight of the pendulum [kg]
J1 = 0.03799; % moment of inertia [Nms^2]
a1 = 0.43; % center of gravity [m]
d1 = 0.006588; % coefficient of friction [Nms]
g = 9.81; % gravity [m/s^2]
dydx = [ y(3)
y(4)
(a*a1*m1*cos(y(1)) + a1*g*m1*sin(y(1)) - d1*y(3))/(J1 + a1^2 *m1)
a ];
% --------------------------------------------------------------------------
function res = one_pendulum_bc(ya,yb,a)
res = [ya(1) - pi
ya(2)
ya(4)
yb(1)
yb(3)];
img: The result should look like this
i just solved it with a model function.
function one_pendulum
options = bvpset('stats', 'on', 'NMax', 3000);
T = 2.5;
sol0 = [
-5.3649
119.5379
-187.3080
91.6670];
solinit = bvpinit(linspace(0, T, T/0.002),[pi, 0, 0, 0], sol0);
sol = bvp4c(#one_pendulum_ode,#one_pendulum_bc,solinit,options, T);
t = sol.x;
ax1 = subplot(2,2,1);
ax2 = subplot(2,2,2);
ax3 = subplot(2,2,3);
ax4 = subplot(2,2,4);
plot(ax1, t, sol.y(1,:))
title(ax1, 'phi');
plot(ax2, t, sol.y(2,:))
title(ax2, 'x');
plot(ax3, t, sol.y(3,:))
title(ax3, 'phi_d');
plot(ax4, t, sol.y(4,:))
title(ax4, 'x_d');
length = size(t)
k = sol.parameters
for i=1:length(2)
k5 = -(k(1) * sin(pi) + k(2) * sin(2*pi) + k(3) * sin(3*pi) + k(4) * sin(4*pi))/sin(5*pi);
x = t(i);
acc(i)=k(1) * sin(pi*x/T) + k(2) * sin(2*pi*x/T) + k(3) * sin(3*pi*x/T) + k(4) * sin(4*pi*x/T) + k5* sin(5*pi*x/T);
end
figure(2)
plot(t,acc)
% --------------------------------------------------------------------------
function dydx = one_pendulum_ode(x,y,k,T)
% Parameter of the One-Pendulum
m1 = 0.3583; % weight of the pendulum [kg]
J1 = 0.03799; % moment of inertia [Nms^2]
a1 = 0.43; % center of gravity [m]
d1 = 0.006588; % coefficient of friction [Nms]
g = 9.81; % gravity [m/s^2]
% Ansatzfunktion
k5 = -(k(1) * sin(pi) + k(2) * sin(2*pi) + k(3) * sin(3*pi) + k(4) * sin(4*pi))/sin(5*pi);
a = k(1) * sin(pi*x/T) + k(2) * sin(2*pi*x/T) + k(3) * sin(3*pi*x/T) + k(4) * sin(4*pi*x/T) + k5* sin(5*pi*x/T);
dydx = [ y(3)
y(4)
(a*a1*m1*cos(y(1)) + a1*g*m1*sin(y(1)) - d1*y(3))/(J1 + a1^2 *m1)
a ];
% --------------------------------------------------------------------------
function res = one_pendulum_bc(ya,yb,k,T)
res = [ya(1) - pi
ya(2)
ya(3)
ya(4)
yb(1)
yb(2)
yb(3)
yb(4)];

how to count foreground segmented faces in image?

i have applied foreground segmentation on an image.its now showing the white areas instead of those faces in original image.now i want to counnt those faces how to do it?? output image is attached.......................................................
close all;
clear all;
clc;
rgbInputImage = imread('Crowd-of-people-008.jpg');
labInputImage = applycform(rgbInputImage,makecform('srgb2lab'));
Lbpdfhe = fcnBPDFHE(labInputImage(:,:,1));
labOutputImage = cat(3,Lbpdfhe,labInputImage(:,:,2),labInputImage(:,:,3));
rgbOutputImage = applycform(labOutputImage,makecform('lab2srgb'));
figure, imshow(rgbInputImage);
figure, imshow(rgbOutputImage);
img=rgbOutputImage;
final_image = zeros(size(img,1), size(img,2));
if(size(img, 3) > 1)
for i = 1:size(img,1)
for j = 1:size(img,2)
R = img(i,j,1);
G = img(i,j,2);
B = img(i,j,3);
if(R > 92 && G > 40 && B > 20)
v = [R,G,B];
if((max(v) - min(v)) > 15)
if(abs(R-G) > 15 && R > G && R > B)
final_image(i,j) = 1;
end
end
end
end
end
end
binaryImage=im2bw(final_image,0.6);
figure, imshow(binaryImage);
binaryImage = imfill(binaryImage, 'holes');
figure, imshow(binaryImage);
%binaryImage = bwareaopen(binaryImage,1890);
%figure,imshow(binaryImage);
%labeledImage = bwlabel(binaryImage, 8);
%blobMeasurements = regionprops(labeledImage, final_image, 'all');
%numberOfPeople = size(blobMeasurements, 1);
%imagesc(rgbInputImage); title('Outlines, from bwboundaries()');
%hold on;
%boundaries = bwboundaries(binaryImage);
%for k = 1 : numberOfPeople
%thisBoundary = boundaries{k};
%plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
%end
%imagesc(rgbInputImage);
%hold on;
%title('Original with bounding boxes');
%for k = 1 : numberOfPeople
%thisBlobsBox = blobMeasurements(k).BoundingBox;
%x1 = thisBlobsBox(1);
%y1 = thisBlobsBox(2);
%x2 = x1 + thisBlobsBox(3);
%y2 = y1 + thisBlobsBox(4);
%x = [x1 x2 x2 x1 x1];
%y = [y1 y1 y2 y2 y1];
%plot(x, y, 'LineWidth', 2);
%end
binaryimage = bwboundaries(binaryimage);
imshow(binaryimage)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(Binaryimage))))
hold on
for k = 1:length(Binaryimage)
boundary = Binaryimage{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
endB = bwboundaries(binaryimage);
imshow(binaryimage)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(Binaryimage))))
hold on
end
for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
end
Use [L, num] = bwlabel(BW, n) to compute num, the number of connected components. See here.
You can use vision.CascadeObjectDetector in the Computer Vision System Toolbox to detect faces without background subtraction.

Color-pass filter by Hue

Why doesn't color filter below find green peppers?
The code:
function [ outhsv ] = ColorFilter( hsv, h, s )
%COLORFILTER Summary of this function goes here
% Detailed explanation goes here
if nargin < 2
h = [];
end
if nargin < 3
s = [];
end
if size(h,2)==1
h = padarray(h, [0 1], 1/100, 'post');
end
if size(s,2)==1
s = padarray(s, [0 1], 1/100, 'post');
end
if isempty(h)
v_of_h = ones(size(hsv,1), size(hsv,2));
else
v_of_h = WeightFunction( hsv(:,:,1), h(:,1), h(:,2));
end
if isempty(s)
v_of_s = ones(size(hsv,1), size(hsv,2));
else
v_of_s = WeightFunctionOnce( hsv(:,:,2), s(:,1), s(:,2));
end
outhsv = hsv;
outhsv(:,:,3) = hsv(:,:,3) .* v_of_h .* v_of_s;
function y = WeightFunction( x, mu, sigma )
%y = WeightFunctionOnce(x,mu,sigma) + WeightFunctionOnce(x-1,mu,sigma);
y = 1 - (1-WeightFunctionOnce(x,mu,sigma)) .* (1-WeightFunctionOnce(x-1,mu,sigma));
function y = WeightFunctionOnce( x, mu, sigma )
if nargin<2
mu=0;
elseif nargin<3
sigma=1./100.;
end
if any(size(mu) ~= size(sigma))
error('mu and sigma should be of the same size');
end
y = zeros([size(x) numel(mu)]);
for i=1:numel(mu)
y(:,:,i) = exp(-((x - mu(i)) .^ 2 ./ (2 .* sigma(i) .^ 2)));
end
%y = sum(y,3)/size(y,3);
y = 1-prod(1-y,3);
Display code:
hue = 120;
h = [hue/360 0.05];
s = [];
rgb1 = imread('huescale.png');
%rgb1 = imread('peppers.png');
hsv1 = rgb2hsv(rgb1);
hsv2 = ColorFilter(hsv1, h, s);
rgb2 = hsv2rgb(hsv2);
bitmask = hsv1(:,:,1)>(h(1)-h(2)) & hsv1(:,:,1)<(h(1)+h(2));
figure;
subplot(3,1,1); imshow(rgb1);
subplot(3,1,2); imshow(rgb2);
subplot(3,1,3); imshow(bitmask);
result on scale
(works)
result on peppers:
(does not)
Why?
If you looked closer at the H values, those green peppers are kind of yellowish, so you might want to widen the rule a bit.
I would suggest something in between 0.15 and 0.5. You can also combine with saturation channel, say only consider portions of images that are vibrant, i.e., we want to get rid of the onions. Try the following codes to get a preview.
hsv_dat = rgb2hsv(imread('peppers.png'));
imagesc(hsv_dat(:,:,1) > 0.15 & hsv_dat(:,:,1) < 0.5 & hsv_dat(:,:,2) > 0.3)
colormap(gray)
You should get