Showing posts with label Matlab. Show all posts
Showing posts with label Matlab. Show all posts

Thursday, May 18, 2017

Plot a branching process in Matlab (branching tree)

Assume you have a realization of a Galton-Watson process (a basic branching process). And you want to plot this realization. The default function in matlab (treeplot) doesn't display this well because of how it handles the depths of the nodes (it will not properly reflect the generation). A matlab user has written an updated function (treetrimplot) which can be found in this suite
https://www.mathworks.com/matlabcentral/fileexchange/2493-simulation-of-stochastic-processes

Additionally, you can the use of treetrimplot here
http://www2.math.uu.se/~ikaj/courses/matlab/rtrees.html

Friday, September 12, 2014

Matlab export graphs, figures

1. I want to find a way to batch export figures ,e.g. if you want it so that every figure produced is outputted in black and white as a pdf file

*I think that there is an option to do this on the CFX.

2. I did find this:
http://www.mathworks.com/matlabcentral/fileexchange/23629-export-fig

Sunday, June 9, 2013

Matlab Output into latex table (Matlab to Latex Table)

This post comments on turning Matlab output into raw latex for inclusion in a latex table, for using \begin{tabular} \end{tabular}.

My preferred way to do this is to use latex.m to convert a Matlab matrix into latex format that can then be posted into tabular.

This is a common problem in simulation studies, where you use Matlab to summarize the results of a simulation study into a table.

I. Caveats regarding my solution:
1. There are probably fancier ways to do this now. I'm using Matlab2latex technology from about 2002. You can check on the central file exchange
2. Also, there might be a way to do this in base-Matlab. I got some file off of Central file exchange. I will note that sometimes a basic solution is very helpful because there are no extra bells/whistles and it is not hard to figure out the options of simple user supplied functions.

II. Other Posted Solutions:
1. http://pundit.pratt.duke.edu/wiki/MATLAB:LaTeX_Table_Writer
2. You can see more advanced ideas in the CFX
http://www.mathworks.com/matlabcentral/fileexchange/index?utf8=%E2%9C%93&term=latex+table
3. matrix2latex seems pretty good too.

III. Dependencies (what file exchange .m files am I using)

IV. My solution

1. use latex.m - This file will output a MATLAB numeric matrix in a format suitable to paste into a LaTeX tabular environment. 
http://www.mathworks.com/matlabcentral/fileexchange/2832-latex
2. internal comment. see gmail FBlog with code. Also, see work from Screening paper.



Tuesday, August 2, 2011

Matlab Simulation - General Discrete Distribution (multivarite)

1. one option is built in randsample with weighted option, you sample with certain weights.

There are CFX options
2. Discrete (multinomial) distribution sampler

http://www.mathworks.com/matlabcentral/fileexchange/25481-discrete-multinomial-distribution-sampler

3. randp
http://www.mathworks.com/matlabcentral/fileexchange/8891

Matlab Simulation: Weighted Without Replacement Sampling

1. matlab's randsample doesn't handle this


Y = RANDSAMPLE(...,true,W) returns a weighted sample, using positive
    weights W, taken with replacement.  W is often a vector of probabilities.
    This function does not support weighted sampling without replacement.

2. Someone on CFX wrote a file for this
http://www.mathworks.com/matlabcentral/fileexchange/27263-modified-randsample
Returns V, a weigthed sample of K elements taken among X without replacement
X a vector of numerics
K amount of element to sample from x
W a vector of positive weights w, whose length is length(x)

3. I think this will take care of multivariate hypergeometric sampling. That is sampling without replacement when there are multiple types, because the different types each have a different probability of being selectted.

Monday, July 4, 2011

string compare in Matlab, strcmp -

http://www.mathworks.com/help/techdoc/ref/strcmp.html
1. Basic Idea
2. full example code



1. Basic Idea
Standard input:
method is a cell
method{1} is the string for the method
method{2} is variable input arguments


method{1} = 'gauss';

 strcmp(method{1}, 'gauss')

2. Full example code

function [y,output] = simResp(method, X, int, beta)
%simResp = simulate response data for regressin models.
%This allows you to simulate regression data from general models.
%NOTES:
%1. It is good to think about the data for observation i
% Here the covariates X_i are the ith row of X (hence 1 x p)
% y_i = X_i beta + ep_i, ep_i \sim N(0,v). Hence:
% y_i \sim N(\mu_i, v), where \mu_i = X_i beta
%2. When you think about it in this form, you see the connection to GLMs
%3. It is best to write a separate function for model and simply have them called inside here;
% it makes error check much easier. e.g. for logistic regression and ordinal logistic regression,
% I'm calling outside functions.
%INPUTS
% *method - 2 x 1 cell. method{1} specifies the regression model to simulate; method{2} will
% contain any additional needed inputs. See methods after Outputs for a description.
% *X - n x p matrix. Design matrix  n replicates and p varibles (does NOT
% include the intercept).
% *beta - p x 1 matrix. covariate vector
% vector.
% *v - positive scalar. The VARIANCE (take square root for standard deviation);
% of the epsilon.
% *int - scalar. the intercept (if you don't want it, set int = 0)
%OUTPUTS
% *y = n x 1 vector. The response vector from the regression (all methods will have this)
% *output - cell. It is an any extra outputs that we might need for certain methods. See the List of methods
% which is given after list of outputs.
%METHODS:
%1. Linear Regression (Gaussian error).
% *method{1} = 'gauss'
% *method{2} = v. positive scalar. The VARIANCE (take square root for standard deviation);
% of the epsilon (in general for linear regression you need to specify the variance of the of errors.
% *output = {}; empty, there is not additional output.
%2. Logistic regression (binary, this with the logistic link)
% *SEE: the function y = simLogReg(int, beta, X)
% *method{1} = 'LR' = logistic regression
% *method{2} = {} (there are no needed extra inputs)
% *output = {}; empty, there is not additional output.
%3. Ordinal logistic regression (right now it only allows for the proportional odds model)
% *SEE: the function [ordata, latdata, newcutoff] =  simOL(Zvector, cutoff)
% *KEY: set cutoff = -1 to generate the cutoff inside the function.
% *method{1} = 'OLR' = Ordinal Logistic Regression
% *method{2}
% *output

if strcmp(method{1}, 'gauss')
    %1. linear regression model
    %remember you need to take square root of v for standard dev.
    y = int + X*beta + normrnd(0,sqrt(method{2}), size(X,1),1);
    output = {};
elseif strcmp(method{1}, 'LR')
    %2. logistic regression
    y = simLogReg(int, beta, X);
    output = {};
elseif strcmp(method{1}, 'OLR')
    %3. ordinal logistic regression
   
    %a) first we need to generate the Zvector in the standard way
    %remember we don't use the intercept here, bc for ordinal the
    %intercept is decided by the cutoff.
    %Zvector = X*beta
       
    %b) now call the function
    [y, latdata, newcutoff] =  simOL(X*beta, cutoff)
    output{1} = latdata;
    output{2} = newcutoff;
else

    error('You have entered an illegal method name; method{1} is not supported by the function')

end

Simulation Set the Seed - Clock the Seed

To clock the seed (remember rand and randn use different seeds, right?)
randn('state', sum(100*clock))
rand('state', sum(100*clock))

But for rand, should you use twister?
http://amath.colorado.edu/computing/Matlab/OldTechDocs/ref/rand.html
rand('state',s) Resets the state to s.
rand('state',0) Resets the generator to its initial state.
rand('state',j) For integer j, resets the generator to its j-th state.
rand('state',sum(100*clock)) Resets it to a different state each time.


Also, see Loren's post on this
http://blogs.mathworks.com/loren/2008/11/13/new-ways-with-random-numbers-part-ii/

Sunday, July 3, 2011

Simulate Discrete Random Variables

Discrete Simulation - simulate from a generic pdf

I should also see my simulation code from Cornell, that I personalized for this problem (if you weren't chosing numbers between 1 and K).

Built in Matlab
1. randi = random integer this is unifrom
2. randsample = weighted

CFX
1. gDiscrPdfRnd - I think this uses mex?
http://www.mathworks.com/matlabcentral/fileexchange/14469-performing-random-numbers-generator-from-a-generic-discrete-distribution
2. randp
http://www.mathworks.com/matlabcentral/fileexchange/8891

Wednesday, March 30, 2011

Matlab Subplot Example Histograms

This is a subplot example with histograms
%I. Start
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear

load RayData
%A         110x4              3520  double   

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%{
%1. horse 1
i=1;
figure(i)
%now plot
hist(A(:,1))

%2. use X in other ones
i=2;
figure(i)
hist(A(:,2))

%3. Figure 3
i=3;
figure(i)
hist(A(:,3))


%4. Figure 4
i=4;
figure(i)
hist(A(:,4))
%}

%Part II. Plot in single subplot
%-----------------------------------------

%Basic Example
%{
figure;
subplot(1,2,1); plot(count(:))
subplot(1,2,2); hist(count(:),5)
datacursormode on

top row (left to right)
>> subplot(2,2,1)
>> subplot(2,2,2)

bottom row (left to right)
>> subplot(2,2,3)
>> subplot(2,2,4)


%}
figure(1);
subplot(2,2,1);  hist(A(:,1)); xlabel('Horse 1', 'fontsize', 16);

subplot(2,2,2); hist(A(:,2)); xlabel('Horse 2', 'fontsize', 16);
subplot(2,2,3); hist(A(:,3)); xlabel('Horse 3', 'fontsize', 16);
subplot(2,2,4); hist(A(:,4)); xlabel('Horse 4', 'fontsize', 16);

Matlab Plot: Multiple KDEs

Below is a script for plotting kernel density estimates (KDEs) in Matlab

%ScriptGraphCombo
%subplot, putting the two on the same graph.

%I. Start
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear

%load in the data;
load data/NB25.mat

%work with  
%X         5000x5             200000  double             
%Y         5000x5             200000  double     

linenu = 2;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Note we can force the support:
%%%%%%%%%%%%%%%%%%%%%
%        x = [randn(30,1); 5+randn(30,1)];
%        xi = linspace(-10,15,201);
%        f = ksdensity(x,xi,'function','cdf');
%%%%%%%%%%%%%%%%%%%%%

%II. Graph - Combined DATA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%this is if you simply use a normal density - keep away from zero
ep=.01;
Y = max(Y,ep);
[fA,xA] = ksdensity(Y(:,1));
[fB,xB] = ksdensity(Y(:,2));
[fC,xC] = ksdensity(Y(:,3));
[fD,xD] = ksdensity(Y(:,4));
[fE,xE] = ksdensity(Y(:,5));

xvector=[xA;xB;xC;xD;xE]';
fvector=[fA; fB; fC; fD; fE]';

plot(xvector, fvector, 'LineWidth',linenu);
legend('avg-1','avg-2', 'avg-3', 'avg-4', 'avg-5')
xlabel('Egg Count', 'fontsize',14)
ylabel('Probability Density', 'fontsize',14)




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Saturday, March 26, 2011

Matlab: Sort Arrays (e.g. sort by a given column)

I can also choose to sort all of A by a particular column. First sort that column, and then use those indices to sort the entire array.
[~, index2] = sort(A(:,2));
Asort2 = A(index2,:)

There is a very nice entry here:
http://blogs.mathworks.com/loren/2010/02/04/constrained-sorting-of-array/

Sunday, March 13, 2011

Matlab Plot Example Change colors and symbols through a for loop

Also, see my gmail for attached function same subject line.


Matlab. control color (colors in a plot).

Some times you want to be able to set your own colors instead of letting the default be determined. A very nice reference is here:
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/symbolPlots.html

A detailed Example:

Here is the symbols all setup:

%2. PLOT
%note:
%1. b = blue
%2. k = black
%For all see:
%http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/symbolPlots.html
colorcell = {'k', 'b','g', 'r', 'y', 'm', 'c', 'w'};
symbolcell ={'.','o', 'x',  '+', '-','*', ':', '-.'};
%plot hold on:
figure(1)

%plot the first value (and then loop over J)
plot(ValCell{1}, IDCell{1}, symbolcell{1}, 'color', colorcell{1})
xlim([0.5 4.5])
hold on;

for i=2:J
  %plot(ValCell{i}, IDCell{i}, 'o','color', colorcell{i})
  plot(ValCell{i}, IDCell{i}, symbolcell{i},'color', colorcell{i})

end

legend('True =1', 'True = 2', 'True = 3', 'True = 4')
hold off;

Very nice reference

http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/symbolPlots.html


function [IndexCell ValCell IDCell] = PlotclassMLR(sampleID, y, yhat, J)
%PlotclassMLR = Plot classify multinomial logistic regression data.
%This gives one way to graphically depict the classification accuracy.
%See the doc folder.
%INPUTS:
% *sampleID - n x 1. Gives the corresponding sample ID for the values in y and yhat.
%Note: when you produce the test set, you can keep the original SampleID
% *y - n x 1. The true response values
% *yhat - n x 1. The corresponding predicted response variables,
% *J - positive integer. Number of categories
%OUTPUTS:
% null - a graph is produced. SampleID vs. predicted label; true labels are show
%by different colors.

%1. Make the indices for each of the true labels.
IndexCell = cell(J,1);
ValCell = IndexCell;
IDCell = IndexCell;
for i=1:J

       %1. %Note IndexCell{j} gives the indices in y which correspond to true label = j
       IndexCell{i} = find(y == i);

       %2. ValCell = value Cell - keep now the yhat, but sorted by the true
       %value. Hence, ValCell{1} gives the predicted values for all of the respnose
       %which have true value = 1.
       ValCell{i} = yhat(IndexCell{i});

       %3. Similarly we need to store the SampleID to plot them
       %(in a simple example, just equal to the index, but in general,
       %sample ID can be different).
       IDCell{i} = sampleID(IndexCell{i});

end


%2. PLOT
%note:
%1. b = blue
%2. k = black
%For all see:
%http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/symbolPlots.html
colorcell = {'k', 'b','g', 'r', 'y', 'm', 'c', 'w'};
symbolcell ={'.','o', 'x',  '+', '-','*', ':', '-.'};
%plot hold on:
figure(1)

%plot the first value (and then loop over J)
plot(ValCell{1}, IDCell{1}, symbolcell{1}, 'color', colorcell{1})
xlim([0.5 4.5])
hold on;

for i=2:J
       %plot(ValCell{i}, IDCell{i}, 'o','color', colorcell{i})
       plot(ValCell{i}, IDCell{i}, symbolcell{i},'color', colorcell{i})

end

legend('True =1', 'True = 2', 'True = 3', 'True = 4')
hold off;