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

Friday, July 19, 2013

bst File Which Handles Multiple Authors (reduces it to et al)

This bst file seems to handle the multiple author issue (listing the first three authors and then compacting the rest with et al).

http://www.biology.emory.edu/Antia/pjohnson/bst/mbe.bst

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.



Sunday, June 10, 2012

Subscript, underscore in Latex

In the equation model, either will work fine. But for inline mathematics you notice a difference. Probalby the operator name isn't needed here, if \max is already defined.
$\max_i$
vs.
$\underset{i}{\operatorname{max}}$

Wednesday, May 23, 2012

Comment Command for Joint Editing

Idea is when we collaborate on a paper it is nice to have a method of leaving comments.

I. Solution write your own commands for each author to make a comment function: author1comment, author2comment.

preamble (need color, anything else?)
\usepackage{color}

commands:
%-----------------------

\def\boxit#1{\vbox{\hrule\hbox{\vrule\kern6pt \vbox{\kern6pt#1\kern6pt}\kern6pt\vrule}\hrule}}
\def\bfred#1{{\color{red}\bf#1}}
\def\bfblue#1{{\color{blue}\bf#1}}
\def\hlred#1{{\color{red}#1}}
\def\hlblue#1{{\color{blue}#1}}


\newcommand{\BHcomment}[1]{\vskip 2mm\boxit{\vskip 2mm{\color{red}\bf#1} {\color{black}\bf -- BH\vskip 2mm}}\vskip 2mm}
\newcommand{\DCcomment}[1]{\vskip 2mm\boxit{\vskip 2mm{\color{blue}\bf#1} {\color{black}\bf -- DC\vskip 2mm}}\vskip 2mm}
\newcommand{\RScomment}[1]{\vskip 2mm\boxit{\vskip 2mm{\color{green}\bf#1} {\color{black}\bf -- RS\vskip 2mm}}\vskip 2mm}


%-----------------------




usage in the body
\BHcomment{Bret writes his comment here. He emphasizes his point with a double exclamation point}

II. There are other solutions:
1. I think there is a track changes package in latex...but I also think I hate this package
2. Good old fashion, Jim gets green, Bob gets red, and Nancy gets blue
pre-amble \usepackage{color}
in text
\textcolor{red}{Here is a comment from Bob, He is *not* happy with this sentence}

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

Saturday, June 18, 2011

cases in latex, absolute value is a standard example

How to make cases in latex

\begin{equation*}
|x|= 
\begin{cases} x & \text{if $x≥0$,}
\\
-x &\text{if $x\le 0$.}
\end{cases}
\end{equation*}

latex stuff about the equal sign


$$
X = ^d Y
$$
This is not a good way to display equal in distribution.

Here is one hack (gotta be a better way). the b here says to put the equal sign on the bottom

$$
3 \begin{array}[b]{c}\alpha\\[-2ex]= \end{array} 5
$$
%b for bottom in \begin{array}[b] to mean the equal sign goes below
% could put it in \be \ee instead of the two dollar signs

latex stuff about the equal sign

$$
X = ^d Y
$$
This is not a good way to display equal in distribution.

Here is one hack (gotta be a better way). the b here says to put the equal sign on the bottom

$$
3 \begin{array}[b]{c}\alpha\\[-2ex]= \end{array} 5
$$
%b for bottom in \begin{array}[b] to mean the equal sign goes below
% could put it in \be \ee instead of the two dollar signs

Tuesday, June 14, 2011

line number correcting in math display - command form

I'd love to make this an environment so I could do begin and end, I couldn't figure this out.

But I do have these options (one acts like equation* the other like eqnarray*)

 %analog for this - begin Line Number; end Line Number
%--------------------------------
\newcommand{\bLN}{\begin{linenomath*} \begin{equation*}}
\newcommand{\eLN}{\end{equation*} \end{linenomath*}}
%--------------------------------






%analog for this - begin Array Line Number; end Array Line Number
%--------------------------------
\newcommand{\baLN}{\begin{linenomath*} \begin{eqnarray*}}
\newcommand{\eaLN}{\end{eqnarray*} \end{linenomath*}}
%--------------------------------
%usage:
%\bLN
%a = b
%\eLN

\baLN
3 &=& 4 \\
&=& 7
\eaLN

Defining your own Environments

You can do this with a hack by defining a new command, e.g. define
 \beq as a short cut for \begin{equation}
and
\eeq as a short cut for \end{equation}

But with a new environment foo you can simply use
\begin{foo}
\end{foo}

Two examples (one is a list so it needs to handle counters):

\newcounter{abc}
\newenvironment{abclist}
   {\begin{list}{(\alph{abc})} {\usecounter{abc}} \setlength{\itemsep}{0pt}
                             
  \setlength{\labelwidth}{4em} }
   {\end{list}}

\newenvironment{solution}{\mbox{}\vspace*{\parskip}\\\sf Solution:}{\rm}
 
Usage:
\begin{abclist}
\item
\item
\item
\end{abclist}

\begin{solution}
Put the solution here
\end{solution}

line numbers. Correction for math display

This problem is described in the style manual
the documentation is attached.
ctan.tug.org/tex-archive/macros/latex/contrib/lineno/ulineno.pdf
From the doc:
lineno.sty does not work well with display math. The parts of a paragraph
preceeding a display math will not get line numbers. The reason is that the
paragraph is not finished, but the part above the display is broken into lines
anyway.

quick answer:
preamble: \usepackage[mathlines]{lineno}
example use in text:
\begin{linenomath*}
$$
\mbox{eff}_i = \frac{X_i - Y_i}{X_i}.
$$
\end{linenomath*}

more complete answer:

\documentclass[11pt]{article}
\usepackage{amssymb,amsmath, amsthm, natbib, subfigure, color,
latexsym, ifthen,commath,setspace}
%\usepackage[draft]{graphicx}
\usepackage{graphicx}
\usepackage{rotating}
%line number has prolems in math mode
\usepackage[mathlines]{lineno}

\begin{document}
\linenumbers

 %example use in text

\begin{linenomath*}
$$
\mbox{eff}_i = \frac{X_i - Y_i}{X_i}.
$$
\end{linenomath*}

Monday, May 9, 2011

R Graphics. Too Small Graphics

How to make these graphics bigger. There is a scale function

scales = list(x=list(relation="free"))

Sunday, May 1, 2011

Latex: Mara Symbol Generator. Draw the symbol

Like the application you can get for the itouch or iphone


http://detexify.kirelabs.org/classify.html

What is this?

Anyone who works with LaTeX knows how time-consuming it can be to find a symbol in symbols-a4.pdf that you just can't memorize. Detexify is an attempt to simplify this search.

How do I use it?

Just draw the symbol you are looking for into the square area above and look what happens!

My symbol isn't found!

The symbol may not be trained enough or it is not yet in the list of supported symbols. In the first case you can do the training yourself. In the second case just drop me a line (danishkirel@gmail.com)!

latex line numbers

A great resource is here
http://www-d0.fnal.gov/Run2Physics/WWW/templates/lineno.html

you can do every 5 numbers if you use \modulolinenumbers[5]

the key is:
\usepackage{lineno}
\begin{document}
\linenumbers

*linenumber command  comes after \begin{document}

Another example with more options:


  Example for D0 PRL template with line numbers printed every 5 lines and starting at 1 for each page:



\RequirePackage{lineno}
\documentclass[aps,prl,twocolumn,showpacs,groupedaddress]{revtex4}  % for review and submission
\usepackage{graphicx}  % needed for figures
\usepackage{dcolumn}   % needed for some tables
\usepackage{bm}        % for math
\usepackage{amssymb}   % for math

\begin{document}
\setpagewiselinenumbers
\modulolinenumbers[5]
\linenumbers
....


Notes:
  • In case that the table of content becomes garbled, add the \linenumbers command after the \tableofcontent command.
  • To increase the font size of the line numbers add

        \def\linenumberfont{\normalfont\small\sffamily}

    (in two column layouts this might have the unwanted effect of line numbers of the right column overlapping with the text in the left column)