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)

R latex interface graphics

From Kevin Eng
http://www.r-bloggers.com/produce-authentic-math-formulas-in-r-graphics/

Thursday, April 28, 2011

Matlab Simulation General Discrete Distribution

1. randp - probably the best
http://www.mathworks.com/matlabcentral/fileexchange/8891
  RANDP - pick random values with relative probability
 
      R = RANDP(PROB,..) returns integers in the range from 1 to
      NUMEL(PROB) with a relative probability, so that the value X is
      present approximately (PROB(X)./sum(PROB)) times in the matrix R.

2. there is this on the FEX - easier to use not as efficient
actually I often use this one for ease.
http://www.mathworks.com/matlabcentral/fileexchange/21912-sampling-from-a-discrete-distribution

sampling from a discrete distribution

The use of this function is easy:
x = discretesample(p, n).
You just input the probability mass, and tell the function how many sample you want to sample, then it returns the samples in form of a 1 x n vector.

3. what about this entry.
[~,x] = histc(rand(1,n),[0;cumsum(p(:))/sum(p)]);

Wednesday, March 30, 2011

latex Table. A multicolumn example

I give a simple example and a more complicated one that needs to use sideways table (because it is too big).

%Example 0. See here
http://andrewjpage.com/index.php?/archives/43-Multirow-and-multicolumn-spanning-with-latex-tables.html

%Example A.

\begin{table}
\caption{Post-treatment Egg Count Varability (Simulated Data). We postulate that the data on a
single farm contains $n=13$ samples from the fixed $p$ model. This table presents such samples at three instances for horses in Table \ref{tbl:prevar} with $p=.95$.\label{tbl:postvar}} %postvar = varab ility in post-treatment count
%we want Hello centered so use c
\begin{center}
\begin{tabular}{cc|ccc}
& & \multicolumn{3}{|c|}{Hello}\\
horse & pre & post (sim 1) & post (sim 2) & post (sim 3) \\ \hline
1 & 3250 & 163 & 167 & 163 \\
2 & 450 & 28 & 26 & 26 \\
3 & 445 & 25 & 21 & 21 \\
4 & 300 & 20 & 17 & 14 \\
5 & 260 & 16 & 9 & 16 \\
6 & 1420 & 73 & 65 & 78 \\
7 & 505 & 20 & 20 & 27 \\
8 & 45 & 4 & 4 & 3 \\
9 & 1230 & 70 & 60 & 59 \\
10 & 325 & 12 & 19 & 14 \\
11 & 325 & 18 & 9 & 22 \\
12 & 100 & 2 & 1 & 2 \\
13 & 80 & 4 & 1 & 1
\end{tabular}
\end{center}
\end{table}

%Example B.
\usepackage{rotate}

You can get away without sideways table here
 \begin{table}
\caption{Post-treatment Egg Count Varability (Simulated Data). We postulate that the data on a
single farm contains $n=13$ samples from the fixed $p$ model. This table presents such samples at three instances for horses in Table \ref{tbl:prevar} with $p=.95$.\label{tbl:postvar}} %postvar = varab ility in post-treatment count
%we want Hello centered so use c
\begin{center}
\begin{tabular}{cc|ccc|ccc|}
& & \multicolumn{3}{|c|}{Hello} & \multicolumn{3}{|c|}{Hello}\\
horse & pre & post (sim 1) & post (sim 2) & post (sim 3) & post (sim 1) & post (sim 2) & post (sim 3) \\ \hline
1 & 3250 & 163 & 167 & 163 & 168 & 210 & 93\\
\end{tabular}
\end{center}
\end{table}

latex Table Example Rotated (sideways?)

An example where you need to present the table in landscape for it to fit 
 
\usepackage{rotating}

\begin{sidewaystable}
\centering
\begin{tabular}{|llllllllp{1in}lp{1in}|}
\hline
Context   &Length   &Breadth/   &Depth   &Profile   &Pottery   &Flint   &Animal   &Stone   &Other    &C14 Dates \\
  &         &Diameter   &        &          &          &        & 
Bones&&&\\
\hline
&&&&&&&&&&\\
\multicolumn{10}{|l}{\bf Grooved Ware}&\\
784 &---   &0.90m &0.18m &Sloping U &P1    &$\times$46  &  $\times$8  &&$\times$2 bone&  2150$\pm$ 100 BC\\
785 &---   &1.00m &0.12  &Sloping U &P2--4 &$\times$23  &  $\times$21 & Hammerstone &---&---\\
962 &---   &1.37m &0.20m &Sloping U &P5--6 &$\times$48  &  $\times$57* & ---&     ---&1990 $\pm$ 80 BC (Layer 4) 1870 $\pm$90 BC (Layer 1)\\
983 &0.83m &0.73m &0.25m &Stepped U &---   &$\times$18  &  $\times$8 & ---& Fired clay&---\\
&&&&&&&&&&\\
\multicolumn{10}{|l}{\bf Beaker}&\\
552 &---   &0.68m &0.12m &Saucer    &P7--14 &---        & --- & --- &--- &---\\
790 &---   &0.60m &0.25m &U         &P15    &$\times$12 & --- & Quartzite-lump&--- &---\\
794 &2.89m &0.75m &0.25m &Irreg.    &P16    $\times$3   & --- & --- &--- &---\\
\hline
\end{tabular}

\caption[Grooved Ware and Beaker Features, their Finds and Radiocarbon
Dates]{Grooved Ware and Beaker Features, their Finds and Radiocarbon
Dates; For a breakdown of the Pottery Assemblages see Tables I and
III; for the Flints see Tables II and IV; for the Animal Bones see
Table V.}\label{rotfloat2} \end{sidewaystable} 

Matlab Plot - Simple example with labeled axes

Matlab Plot - Simple example with labeled axes and changing other options.
Figure example

%GraphScriptfinal
%use thickline and label y,x

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

load 'matdata.mat'
% whos
%   A         60x1               480  double             
%   B         30x1               240  double             
%   C         20x1               160  double                  

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

%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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% %standard call:
% [f,xi] = ksdensity(x, 'support', [0,1]);
% plot(xi,f);

%Put all 64 Farms together
figure(1)
[fA,xiA] = ksdensity(A, 'support', 'positive');
[fB,xiB] = ksdensity(B, 'support', 'positive');
[fC,xiC] = ksdensity(C, 'support', 'positive');
% plot(xiA,fA)
% hold on
% plot(xiB,fB)
% hold on
% plot(xiC,fC)
% legend('1-avg','2-avg','3-avg')

linenu = 2;

plot(xiA,fA,xiB,fB,xiC,fC, 'LineWidth',linenu);
legend('1-avg','2-avg','3-avg')
xlabel('Egg Count', 'fontsize',14)
ylabel('Probability Density', 'fontsize',14)




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

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;

 

Saturday, March 5, 2011

Subfigure. Example of using Subfigure (need to update)

%This entry gives an example of using the subfigure package. Together with the iften to conditionally include graphs. The first figure gives an example without subfigure

%This needs to be updated to find a true subfigure example

%preamble

\usepackage{graphicx, subfigure, ifthen}

%Figures:
%-----------------------------------------------
\newboolean{includefigs}
\setboolean{includefigs}{true} %true = show graphs or false = don't
\newcommand{\condcomment}[2]{\ifthenelse{#1}{#2}{}}
%-----------------------------------------------

%main document

\condcomment{\boolean{includefigs}}{
\begin{figure}[t!]
\begin{center}
\includegraphics[scale=.3]{LHflo.eps}
\includegraphics[scale=.3]{LHmv.eps}
\includegraphics[scale=0.3]{LHhW.eps}
\caption{LH experiment. (L) plot of log $\flo$ versus cycle number ($\log F_j$ vs. $j$) for all 16 replicates of $LH_1$ (in blue) and all 16 replicates of $LH_2$ (in red); (C) the mean and variance (taken over the 15 replicates, which were retained for the data analysis, at each cycle) of log $\flo$ versus cycle number for $LH_1$ (blue) and $LH_2$ (red); (R) plot of $\hat{V}_k$ ($\times 10^7$) versus replicate number for $LH_1$ ($+$) and $LH_2$ ($o$).\label{fig:LH}}
\end{center}
\end{figure}
}

Sunday, February 27, 2011

Latex Blogs - other blogs

1. this one is great
http://texblog.wordpress.com/

2. this is not a blog but a list of very specific tricks. Jakob's Latex Tricks
http://dcwww.camd.dtu.dk/~schiotz/comp/LatexTips/LatexTips.html

Saturday, February 26, 2011

Latex: Commenting out a Figure (comment out)

Latex: Commenting out a Figure

Comment out a figure


Note: I'm reposting some of blog posts now that the blog is searchable. It does not seem that the old posts show up in the search...

Sometimes it is helpful to typeset your documents without including the figures. For instance,
1. You want to share your .tex with someone but don't want to send them all of your eps figures.
2. You have one million figures in your document and this will allow you to compile it faster.

One solution is the following. You can use the ifthen package to comment out figures, by setting a global boolean at the head of your document.

Here are some latex details.

%Document Preamble
\usepackage{epsfig,graphicx, ifthen}

\newboolean{includefigs}
\setboolean{includefigs}{false} %true = show graphs or false = don't
\newcommand{\condcomment}[2]{\ifthenelse{#1}{#2}{}}

%Usage Example
\condcomment{\boolean{includefigs}}{
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.4]{Fig.eps}
\end{center}
\vskip -0.2in
\caption{Fun with graphics}
\end{figure}

Wednesday, February 23, 2011

bst styles. Bibtex different styles

This website is pretty comprehensive (see the pdf file). You can see which styles produce what type of bibliography, e..g maybe you want references sorted by the order they appear in your paper.

http://amath.colorado.edu/documentation/LaTeX/reference/faq/bibstyles.html

CV with latex and bibtex (vitae). Curriculum Vitae

One issue is creating CV's with bibtex, there is an easy hack which is simply to use the .bbl file and then paste this into your latex file. Also you want to use the multbib package to allow multiple styles.

I think this is the best:
http://phaselockfel.blogspot.com/2009/03/prepare-resume-using-latex-and-bibtex.html

There is some good advice here:

http://tex.stackexchange.com/questions/4485/how-should-one-use-write18-with-bibtex

http://linux.dsplabs.com.au/resume-writing-example-latex-template-linux-curriculum-vitae-professional-cv-layout-format-text-p54/

http://www.matthewjmiller.net/howtos/create-a-curriculum-vitae-using-latex/

http://www.matthewjmiller.net/howtos/create-a-curriculum-vitae-using-latex/

Friday, February 18, 2011

Latex. Comment out

Multiline comment in latex. There are many options for this (instead of using "%" at each line).

A simple solution is to define a command in the header.
\newcommand{\comment}[1]{}

Usage.
\comment{
This is all crap that I don't want to actually appear in the paper, so I will comment it out
}

Tuesday, February 15, 2011

Links Latex

1.Really nice for R and latex

http://www.wekaleamstudios.co.uk/

R: lme and lmer Basic Functionality

R: lme and lmer Basic Functionality

This is just a quick reference to someone else's work. First of all the basics:
1. lme
http://stat.ethz.ch/R-manual/R-patched/library/nlme/html/lme.html
2. lmer
http://cran.r-project.org/web/packages/lme4/index.html

Professor Vardeman (Iowa State) has posted a very nice summary for the basic functionality of these functions. It is important to heed is warning that these functions are constantly under development (which is generally applicable to R).
http://www.public.iastate.edu/~vardeman/stat511/stat511.html
search for: lme() and lmer() Functionality (4/17/09)

Latex Indicator Function

$$
1{\hskip -2.5 pt}\hbox{I} \qquad \qquad
$$

Great Latex Page

http://www.statslab.cam.ac.uk/~elie/ext/tex/

LaTeX Lecture Notes and Summaries

1. MPhil (and Part III) LaTeX Lecture Notes (PDF),
2. LaTeX Summary "Cheat" Sheet (PDF) and Maths Summary (PDF),
3. LaTeX "Not So Short Introduction" (PDF) and Wikipedia Book (PDF).

Diagam and Picture Templates

1. Diagram Templates in TeX, LaTeX,
2. Grid (with Coordinates) Template in TeX,
3. Encapsulated Postscript (EPS) to plain Postscript LaTeX Template.

Tex and LaTeX Tabulation Templates

1. Table Templates in TeX, LaTeX,
2. Two pages per side in Landscape Mode LaTeX Template.

Example Code with Overlaps

1. TeX Code example to produce Indicator Function Symbol,
and elongated Minus Signs (also valid in LaTeX).

Monday, January 24, 2011

bibtex from Google Scholar

How do I import a Bibtex citation from Google Scholar into my .bib file?

http://answers.yahoo.com/question/index?qid=20080711124719AAr8dyK