⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 genmix.m

📁 GUI FOR GENERATING MULTIVARIATE RANDOM VARIABLES FROM MIXTURE的matlab实现
💻 M
📖 第 1 页 / 共 2 页
字号:
answer  = inputdlg(prompt,title,1,def); 

if ~isempty(answer)
	mus = zeros(ndim,ncomp);
	for i = 1:ncomp
		eval(['tmp = [' answer{i} '];'])
		if length(tmp)==ndim
			eval(['mus(:,i) = [' answer{i} ']'';']);
		else
			errordlg('The number of entries in the mean is incorrect.','Dimensionality Error')
			return
		end
	end
else
	% If the user pushes cancel, then set the means to the current value.
	mus = H.means;
end

H.means = mus;
set(H.fig,'userdata',H)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   ENTER THE COVARIANCE MATRICES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function entercovs(H)
ndim = get(H.dims,'value')+1;
ncomp = get(H.ncomp,'value');
title='Input for Covariance Matrices';
model = get(H.model,'Value');
M = [model{:}];
flag = find(M);

% Note that the covariance matrices will be kept in a
% 3-D array - each dxd page is a covariance matrix for a component.
switch flag
case 1
	% Model 1 - common diagonal covariance matrices.
	% equal variance across terms.
	covs = zeros(ndim, ndim, ncomp);
	def = {'1'};
	prompt = {'Enter the variance for the components:'};
	answer = inputdlg(prompt,title,1,def);
	if ~isempty(answer)
		for i = 1:ncomp
			covs(:,:,i) = str2num(answer{1})*eye(ndim);
		end
	else
		% Reset to current value.
		covs = H.covms;
	end
case 2
	% Model 2 - spherical - unequal - sigma_k*I
	covs = zeros(ndim,ndim,ncomp);
	prompt = cell(ncomp,1);
	def = cell(ncomp,1);
	for i = 1:ncomp
		% Set up the strings for the dialog box.
		prompt{i} = ['Enter the variance for component ' int2str(i)];
		def{i} = '1';
	end
	answer  = inputdlg(prompt,title,1,def); 
	
	if ~isempty(answer)
		% Now set up the covariance matrices.
		for i = 1:ncomp
			covs(:,:,i) = str2num(answer{i})*eye(ndim);
		end
	else
		% Reset to current value.
		covs = H.covms;
	end
case 3
	% Model 3 - same covariance (full) matrix for each component
	covs = zeros(ndim,ndim,ncomp);
	prompt = cell(ndim,1);
	def = cell(ndim,1);
	title = 'Enter the covariance matrix ...';
	% set up strings for dialog box.
	tmpcov = eye(ndim);

	for i = 1:ndim
		prompt{i} = ['Enter the elements of row ' int2str(i) ' of the covariance matrix, separated by commas or blanks:'];
		tmp = mat2str(tmpcov(i,:));
		n = length(tmp);
		def{i} = tmp(2:(n-1));
	end
	answer = inputdlg(prompt,title,1,def);
	
	if ~isempty(answer)
		tmp = zeros(ndim,ndim);
		for i = 1:ndim
			eval(['tmp(i,:) = [' answer{i} '];']);
		end
		for i = 1:ncomp
			covs(:,:,i) = tmp;
		end
	else
		% Reset to current value.
		covs = H.covms;
	end
	
otherwise

	% unconstrained model
	covs = zeros(ndim,ndim,ncomp);
	prompt = cell(ndim,1);
	def = cell(ndim,1);
	% set up strings for dialog box.
   
    tmpcov = eye(ndim);
    for j = 1:ndim
        prompt{j} = ['Enter the elements of row ' int2str(j) ' of the covariance matrix, separated by commas or blanks:'];
        tmpm = mat2str(tmpcov(j,:));
        n = length(tmpm);
        def{j} = tmpm(2:(n-1));
    end
    
    for i = 1:ncomp
        tmp = zeros(ndim,ndim);
        
        answer = inputdlg(prompt,['Enter covariance matrix ' int2str(i)'], 1, def);
        if ~isempty(answer)
            for j = 1:ndim
                eval(['tmp(j,:) = [' answer{j} '];']);
            end
            covs(:,:,i) = tmp;
        else
            % Reset to current value.
            covs = H.covms;
        end
    end		
end

H.covms = covs;
set(H.fig,'userdata',H)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   GENERATE RANDOM VARIABLES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function genrvs(H)
% Write the function to generate the required random variables.
% First get the parameters.
pies = H.weights;
mus = H.means;
covs = H.covms;
n = str2num(get(H.nobs,'string'));
ndim = get(H.dims,'value')+1;
ncomp = get(H.ncomp,'value');

if length(pies) ~= ncomp
    % Then number of elements is not correct.
    errordlg('The number of weights is incorrect.','Data Entry Error')
	return
end

[nd,nc] = size(mus);
if nd~=ndim | nc~=ncomp
    errordlg('The number of means is incorrect.','Data Entry Error')
    return
end

% Now find out how many are in each term.
r = rand(1,n);
N = zeros(ncomp,1);
cpies = cumsum(pies);
N(1) = length(find(r < cpies(1)));
for i = 2:(ncomp-1)
	N(i) = length(find(r >= cpies(i-1) & r < cpies(i)));
end
N(ncomp) = n - sum(N);

% Now call the function that many times. 
data = zeros(n,ndim);
cN = cumsum(N);
data(1:N(1),:) = csmvrnd(mus(:,1),covs(:,:,1),N(1));
for i = 2:ncomp
	data(cN(i-1)+1:cN(i),:) = csmvrnd(mus(:,i),covs(:,:,i),N(i));
end
	
H.data = data;
set(gcf,'userdata',H);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   SAVE TO THE WORKSPACE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function saveworkspace(H)
% Write function to save the data set to the workspace.

if isempty(H.data)
	errordlg('You have not generated any variables yet.','GUI Error')
	return
end

prompt = {'Enter the name for the variable:'};
title = 'Set Variable Name';
def = {'data'};
answer = inputdlg(prompt,title,1,def);
if ~isempty(answer)
	assignin('base',answer{1},H.data)
else
	assignin('base','data,H.data')
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   SAVE TO A FILE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function savefile(H)
% Write a function to save the data set to a text file.

if ~isempty(H.data)
    data = H.data;
else
    errordlg('You have not generated any variables yet.','GUI Error')
	return
end

[filename,pathname] = uiputfile('*.txt','Save As Text File');

if filename ~= 0
	eval(['save ' [pathname, filename] ' data -ascii'])
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	PLOT THE DATA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotdata(H)
figure

if ~isempty(H.data)
    plotmatrix(H.data);
else
    errordlg('You have not generated any variables yet.','GUI Error')
    return
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	GENERATE THE RV'S FOR A TERM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = csmvrnd(mu,covm,n)
% CSMVRND Generate multivariate normal random variables.
%
%   R = CSMVRND(MU,COVM,N) Generates a sample of size N
%   random variables from the multivariate normal 
%   distribution. MU is the d-dimensional mean as a 
%   column vector. COVM is the d x d covariance matrix.
%
%   W. L. and A. R. Martinez, 9/15/01
%   Computational Statistics Toolbox 
if det(covm) <=0
    % Then it is not a valid covariance matrix.
    errordlg('The covariance matrix must be positive definite','Covariance Error')
	return
end

if ~isequal(covm,covm')
	% Then it is not symmetric
	errordlg('The covariance matrix must be symmetric.','Covariance Error')
	return
end

mu = mu(:); % Just in case it is not a column vector.
d = length(mu);
% get cholesky factorization of covariance
R = chol(covm);
% generate the standard normal random variables
Z = randn(n,d);
X = Z*R + ones(n,1)*mu';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	VIEW CURRENT MEANS IN COMMAND WINDOW
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function viewmeans(H)
mus = H.means;
[ndim,ncomp] = size(mus);

for i = 1:ncomp
    disp('HIT ANY KEY TO CONTINUE...')
    disp(['The mean for component ' int2str(i) ' is:'])
    disp(mus(:,i)')
    pause
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	VIEW CURRENT COVARIANCES IN COMMAND WINDOW
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function viewcovs(H)
covs = H.covms;
ncomp = get(H.ncomp,'value');

for i = 1:ncomp
    disp('HIT ANY KEY TO CONTINUE ...')
    disp(['The covariance for component ' int2str(i) ' is:'])
    disp(covs(:,:,i))
    pause
end

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -