MATLAB nuggets
1) How to initialize cell arrays
k = cell(100,1);
2) Playing with cell arrays
>> c{1} = [1,2]
c = [1x2 double]
>> c{2} = ['a']
c = [1x2 double] 'a'
>> c
c = [1x2 double] 'a'
>> c = {[1 2], ['a']}
c = [1x2 double] 'a'
>> state_mu = cell(2,1)
state_mu =
[]
[]
>> state_mu{1} = [4 5 6]
state_mu =
[1x3 double]
[]
>> state_mu{1}(3)
ans =
6
v_data1 = [1 2 3 4]; v_data2 = [3 8 9]; v_data3 = [12 7 3];
v_data = {v_data1,v_data2,v_data3};
whole_virus_data1 = [v_data1 v_data2 v_data3]; % equivalent to the next statement
whole_virus_data2 = [v_data{:}]
>> state_mu = cell(5,10)
>> >> state_mu{1,3} = [1 2 3]
state_mu =
[] [] [1x3 double] [] [] [] [] [] [] []
[] [] [] [] [] [] [] [] [] []
[] [] [] [] [] [] [] [] [] []
[] [] [] [] [] [] [] [] [] []
[] [] [] [] [] [] [] [] [] []
Concatenate different cell arrays to create a single array
[state_mu{1:3,4}]
Summing cell array rows (from Loren on the art of Matlab, Summing cell rows, link)
>> state_mu{1,4} = [19 3 24 1]
>> state_mu{2,4} = [19 3 24 1]
>> >> reshape([state_mu{1:3,4}],[],2)
ans =
19 19
3 3
24 24
1 1
>> sum( reshape([state_theta{1:3,4}],[],2), 2)
ans =
38
6
48
2
>> file_name{1,:}
ans =
gendata_generate_data_1_1_19-Sep-2012.tex
ans =
gendata_generate_data_1_2_19-Sep-2012.tex
ans =
gendata_generate_data_1_3_19-Sep-2012.tex
>> {file_name{1,:}}
ans =
[1x41 char] [1x41 char] [1x41 char]
3) How to remove NaN from an array (a column vector here)
MLHdata = [1 NaN 2 3 78 NaN 86]'
MLHdata(any(isnan(MLHdata),2),:) = [10]
AND
% to specifically change a column vector which has NaNs and substitute that with some other number
% in this example, we substitute the NaNs in the 17th column of a matrix with another number
data_ptr.data(any(isnan(data_ptr.data(:,17)),2),17) = [-100]
AND
y = [ 1 13 NaN 34 NaN 45]; size(y)
y(find(isnan(y))) = []
size(y)
% array will now shrink in size (TRICK to remove NaN or other elements in array without shuffling elements around)
4) Matlab tutorial on curve fitting to ODE (by Drew Levin)
5) How to run matlab on a remote machine (courtesy Joshua Hecker)
ssh into machine
nohup matlab < myfile.m &
6) How to save a plot/figure automatically (courtesy Drew Levin)
figID = figure;
hist(state_theta1(:,4),1000)
xlabel('log_1_0 delta');
title('Histogram');
print(figID, '-djpeg', sprintf('delta_hist_%d_%s.jpg', N, date));
% OR
print(figID, '-dpdf', sprintf('test_%s.pdf', date));
% OR if you want to save current figure
saveas(gcf,'star.eps', 'psc2')
7) Display text
disp(['Simulating group ', num2str(iDoseGrp), ' ... '])
8) Call external program from Matlab (untested, taken from Matlab Newsreader forum link)
matlabpool(4);
parfor (i=1:4)
system(['H:\Mat_cod\Program\ssvv.exe', ' ', '-f', ' ', strcat('H:\Mat_cod\folder', num2str(i), '\rundata.txt')]); % Parallel run 4 applications
end
matlabpool close;
9) Getting taskid in parfor loop (from Matlab Newsreader forum link)
parfor ii = 1:100
t = getCurrentTask();
tid(ii) = t.ID;
end
10) Error handling/debugging tips (from Matlab Newsreader forum link)
"dbstop if all error" and "err.getReport()"
11) Other text importing functions
xlsread, textscan
12) Matlab command to pause execution (and wait for command/keystroke)
pause (link)
13) Matlab code to get current function name (from which it is being executed, courtesy link)
[ST,~] = dbstack();
function_name = ST.name
14) Matlab code using find
ind = find(combined(:,1) == 2.3e5);
mod_combined = combined(ind,:)
% size(mod_combined)
find(mod_combined(:,2) == 4)
15) Repeatedly add same element to array
Use repmat
a = [10; 10; 10; 10; 10;]
% add 17 to last column
[a repmat(17,size(a,1),1)]
% another example code
repmat(17, 1, 10)
> 17 17 17 17 17 17 17 17 17 17
16) Minimum of array (only non-zero elements)
% first crack; does not handle non-zero
[~, index] = min(output_array(:,5)); % 5th column has SSR
best_V0 = output_array(index,1)
% handle non-zero
[~, index] = min(output_array(find(output_array(:,5) > 0),5));
best_V0 = output_array(index,1)
16) Creating a structure array
patient.name = 'John Doe'; patient.billing = 127.00; patient.test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50; patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
patient
17) Concatenating to a list
g_temp = [17 8 23];
temp = []
for jCount = 1:3
temp = [temp g_temp(jCount)]
end
18) Playing with cell arrays (how to rowwise mean of 2D cell array)
draw_indiv_param =
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
> draw_indiv_param{1,:}
ans =
3.9079 0.3030 -0.3871
ans =
4.0995 0.2978 -0.4733
ans =
4.0461 0.3051 -0.4551
> [draw_indiv_param{1,:}]
ans =
3.9079 0.3030 -0.3871 4.0995 0.2978 -0.4733 4.0461 0.3051 -0.4551
> iNumParam = 3;
mean(reshape([draw_indiv_param{1,:}],iNumParam,[]),2)
ans =
4.0178
0.3020
-0.4385
19) Colour in bar plots and text in X axis label (modified from link and link)
array=[ 1 2 3 ; 4 5 6 ; 7 8 9];
handle_bar = bar('v6',array);
set(handle_bar(1),'facecolor','red')
set(handle_bar(2),'facecolor',[0 1 0])
set(handle_bar(3),'facecolor','b')
set(gca,'XTickLabel',{'first', 'second', 'third'})
20) command to check where Matlab is installed
>> matlabroot
ans =
/usr/local/MATLAB/R2011a
21) command to check version
>> version
ans =
7.12.0.635 (R2011a)
22) How to convert a matlab (.m) file to MEX (on Ubuntu) Matlab version 7.12.0.635 (R2011a)
say you have a file named poc_gibbs_birds_v121allcall.m
type this at the Unix command prompt
> matlab
type this at Matlab command prompt
> mcc –m poc_gibbs_birds_v121allcall.m
type this at Matlab command prompt
> exit
OR
just type this at command prompt
> /usr/local/MATLAB/R2011a/bin/mcc -mv poc_gibbs_birds_v121allcall.m
THEN
type this at Unix command prompt
ls -ltr
a file named run_poc_gibbs_birds_v121allcall.sh should be created
type this at Unix command prompt
./run_poc_gibbs_birds_v121allcall.sh /usr/local/MATLAB/R2011a
OR
nohup ./run_poc_gibbs_birds_v121allcall.sh /usr/local/MATLAB/R2011a
where /usr/local/MATLAB/R2011a is the path to Matlab.
you can find this by entering matlabroot in the Matlab command prompt
23) How to suppress MATLAB warnings
Right-click on a MATLAB error. It will show options to suppress in the current file, all files, or in this line.
It will then add a comment to the end of that line.
24) Histograms with multiple colours
[nR0_P xR0_P] = hist(log10R0_P,100);
[nR0_NP xR0_NP] = hist(log10R0_NP,100);
figure
bar(xR0_P,nR0_P,'r')
hold on
bar(xR0_NP,nR0_NP,'b')
hold off
25) filter a file on some field and display minimum of some other field after filtering
filter by 7th column < 30
from this result, find minimum of 6th column
min(fid_filename( find(fid_filename(:,7) < 30) ,6))
26) Initialize array with a sequence of numbers with some step size/difference
>> [0:5:20]
ans =
0 5 10 15 20
27) Calling UNIX/shell commands from matlab
system('sed ''1d'' header.csv > noheader.csv')
28) Shell script to iterate through directories (handles directories with spaces) and compiles matlab code in each of these directories (inspired by stackoverflow)
#!/bin/bash
# Shell script to iterate through directories in pwd
for dir in */
do
echo $dir
# go to directory
cd "$dir"
# run mcc to compile matlab code
pwd
/usr/local/MATLAB/R2011a/bin/mcc -mv unixfile.m
# /opt/matlab/bin/mcc -mv unixfile.m
# go back to parent directory
cd ..
done
29) Shell script to compile matlab code, wait (delay) and then run compile code
#!/bin/sh
# compile code
/usr/local/MATLAB/R2011a/bin/mcc -mv unixfile.m
# delay: verify if compilation worked
sleep 10
# execute compiled code
nohup ./run_unixfile.sh /usr/local/MATLAB/R2011a
30) Replicate one number many times to create a vector
number_of_times_replicate = 100
ones(1,number_of_times_replicate) * 17
31) Use plotyy to plot on two y axes
[AX,H1,H2] = plotyy(t,V,t,zT/target,'plot')
set(get(AX(1),'Ylabel'),'String','Virus titer (log_1_0 PFU/mL)','fontsize',25,'color','black')
set(get(AX(2),'Ylabel'),'String','Target cell abundance','fontsize',25,'color','black')
set(AX(1),'ycolor','black','YLim',[-2.2 4],'YTick',[-2:1:4])
set(AX(2),'ycolor','black','YLim',[0 1],'YTick',[0:0.1:1])
% set(AX(2),'ytick',[])
% set(AX(1),'ytick',[])
set(AX(2),'fontsize',16)%,'YTick',[0:0.1:1])
set(AX(1),'fontsize',16)
% set(AX(2),'YTickLabel',[]);
% set(AX(2),'ycolor','black','YLim',[0 1],'YTick',[0:0.1:1])
set(H1,'LineStyle','-','LineWidth',2,'Color','black')
set(H2,'LineStyle','-','LineWidth',2,'Color','blue')
xlabel('Days post infection','fontsize',25);
%% get more data after computations
[AX,H1,H2] = plotyy(t,V,t,zT/target,'plot')
% hold(AX(1))
set(H1,'LineStyle','--','LineWidth',2,'Color','black')
set(H2,'LineStyle','--','LineWidth',2,'Color','blue')
set(AX(1),'ycolor','black','YLim',[-2.2 4],'YTick',[-2:1:4])
set(AX(2),'ycolor','black','YLim',[0 1],'YTick',[0:0.1:1])
set(AX(2),'fontsize',16)
%% then you will see there are multiple tick marks on right hand side Y-axis where X-axis tick marks are. I use insert text box (white colour) to paint over those extra ticks
32) Launching multiple instances of MATLAB on a Mac
Open Terminal
Type "/Applications/MATLAB_R2010bSP2.app/bin/matlab" at the command prompt
33) Basic image analysis/processing
a = imread('image_stable.tif',11); size(a)
K = mat2gray(a);
imshow(a), figure, imshow(K)
34) To convert a cell array of strings (such as might have been obtained after importdata on file that has some text columns) into numbers
use str2double
35) Write/output array to csv file
csvwrite('test.csv',array);
OR
% write to an excel file
xlswrite('test.xls',temp_array);
% xlswrite('test.txt',temp_array) % would work also
36) Converting to a cell array of strings (mathworks)
label = [ 'P '; 'P '; 'P '; 'P '; 'P '; 'P '; 'P '; 'P '; 'P '; 'NP'; 'NP'; 'NP'; 'NP'; 'NP'; 'NP'; 'NP'; 'NP';]
species = cellstr(label)
37) Function to save all workspace variables to a .mat file
save(filename)
38) Matlab image processing function
bwmorph
31) Analyzing gene expression data using bioinformatics toolbox
Representing gene expression data values in DataMatrix object
Perform two-sample t-test using mattest
c = [190 100; 189 120; 145 134; 140 156]
d = [1000 1100; 1200 1145; 1300 1234; 1134 1453]
PValues = mattest(c,d)
FDR = mafdr(PValues)
mavolcanoplot(c,d, PValues)
Estimate false discovery rate using mafdr
List of functions in bioinformatics toolbox
Note: for FDR by Bejamini-Hochberg method use
FDR = mafdr(PValues, 'BHFDR', true)
32) A practical example of using mattest (bioinformatics package)
data_ptr_healthy = importdata('combined_healthy_compound_preds.txt')
data_ptr_disease = importdata('combined_disease_compound_preds.txt')
PValues = mattest(data_ptr_healthy.data,data_ptr_disease.data,'VarType','unequal','permute',true,'showplot',true,'showhist',true)
FDR = mafdr(PValues)
mavolcanoplot(data_ptr_healthy.data, data_ptr_disease.data,PValues)
index_sign = find(FDR < 0.05)
data_ptr_healthy.textdata{index_sign}
csvwrite('list_FDR.txt',FDR)
33) Another example of mattest (t-test) but with the DataMatrix object
function basic_t_test_datamatrix()
% implements a basic t-test with data matrix objects
%% import data
data_ptr_healthy = importdata('combined_healthy_compound_predictions.txt')
data_ptr_disease = importdata('combined_disease_compound_predictions.txt')
import bioma.data.*
%temp = [1:10]
%dmo_healthy = DataMatrix(data_ptr_healthy.data,data_ptr_healthy.textdata,temp)
dmo_healthy = DataMatrix(data_ptr_healthy.data,data_ptr_healthy.textdata,[1:size(data_ptr_healthy.data,2)])
%temp_2 = [1:87]
%dmo_disease = DataMatrix(data_ptr_disease.data,data_ptr_disease.textdata,temp_2)
dmo_disease = DataMatrix(data_ptr_disease.data,data_ptr_disease.textdata,[1:size(data_ptr_disease.data,2)])
[p_value t_scores] = mattest(dmo_healthy,dmo_disease,'showplot',true,'showhist',true)
%% downstream analysis FDR, volcano plot etc
FDR = mafdr(p_value)
mavolcanoplot(data_ptr_healthy.data, data_ptr_disease.data,p_value)
% index_sign = find(FDR < 0.05)
% data_ptr_healthy.textdata{index_sign}
% %csvwrite('list_diff_expr_compounds.txt',data_ptr_healthy.textdata{index_sign})
% csvwrite('list_FDR.txt',FDR)
index_sign = find(p_value < 0.05)
data_ptr_healthy.textdata{index_sign}
%csvwrite('list_diff_expr_compounds.txt',data_ptr_healthy.textdata{index_sign})
%csvwrite('list_p_value_datamatrix.txt',PValues)
34) Code to create box plots (with notch) on disease vs healthy data
data_ptr_healthy = importdata('combined_healthy_compound_preds.txt')
data_ptr_disease = importdata('combined_disease_compound_preds.txt')
data_box_plot = [ data_ptr_healthy.data(27,:)' ; data_ptr_disease.data(27,:)']
% number of sample ids/replicates
%group = [repmat('healthy',10,1); repmat('disease',87,1)]
group = [repmat('healthy',size(data_ptr_healthy.data,2),1); repmat('disease',size(data_ptr_disease.data,2),1)]
figure;
boxplot(data_box_plot,group,'notch','on')
% title command must come AFTER boxplot command
title('Glutathione')
% On another note, if you need to do something fancy (like rotate labels etc) see this on MATLAB File Exchange
35) Hash tables/dictionaries in MATLAB (adapted from response by Amro in stackoverflow)
PRISM_predictions = importdata('list_diff_expr_compounds_PRISM_pvalues.txt');
PRISM_predictions.data
key_PRISM = PRISM_predictions.data;
values_PRISM = PRISM_predictions.textdata;
PRISM_Map = containers.Map(key_PRISM,values_PRISM);
RISK_predictions = importdata('list_diff_expr_compounds_PRISM_pvalues.txt');
RISK_predictions.data
key_RISK = RISK_predictions.data;
values_RISK = RISK_predictions.textdata;
RISK_Map = containers.Map(key_RISK,values_RISK);
36) Other string related functions
char
cellstr
37) A great resource on t-test and potential pitfalls in MATLAB (link)
38) Regular expressions
(A) Simple calse
cmp_name = 'C15678 glujatho'
>> regexpi(cmp_name,'C15679*','end')
ans =
5
# 'end' option returns the end index if there is a match
# so if the length of the compound name is 6 characters, then
# you want to test if regexpi with 'end' option returns 6
if regexpi(cmp_name,'C15679*','end')
disp('found')
else
disp('not found')
end
(B) A more complicated case (regexpi could return a cell array sometimes)
temp_result = regexpi(file_ptr.textdata(iInnerCount,iCompound_Name_fullKEGG_SHOTGUN),(temp_name_halfkegg_metabol),'end');
if ~isempty(temp_result{1}) && temp_result{1} == 6
disp('found')
else
disp('not found')
end
39) Paired/matched t-test
%% do a paired t-test on predicted compounds and metabolomics data
[ttest_unpaired_hvalue ttest_unpaired_pvalue] = ttest(log10(healthy_array(:,1)),log10(healthy_array(:,2)))
40) Test for normality (Jarque-Bera test)
[h_value p_value] = jbtest(x_data)
41) Wilcoxon rank-sum test
ranksum()
Example:
[temp_p_value temp_h_value temp_wilcox_stats] = ranksum( ...
file_ptr.data(iCount - iNum_metadata_rows,iExtent_RISK_healthy), ...
file_ptr.data(iCount - iNum_metadata_rows,iExtent_RISK_ibd) ...
)
% needs a vector not matrix
% more elaborate example with a for loop iterating through a matrix
data_ptr_healthy = importdata('healthy.csv');
data_ptr_disease = importdata('disease.csv');
iTempCount = 1;
for iCount = 1:size(data_ptr_healthy.data,1)
[temp_p_value temp_h_value temp_wilcox_stats] = ranksum( ...
data_ptr_healthy.data(iCount,:), ...
data_ptr_disease.data(iCount,:) ...
)
array_wilcox_risk(iTempCount,:) = [temp_p_value temp_h_value temp_wilcox_stats.ranksum]
iTempCount = iTempCount + 1;
end
42) Convert linearize a matrix into a vector
>> a = [ 1 2; 13 45; 23 -19]
a =
1 2
13 45
23 -19
>> reshape(a,1,6)
ans =
1 13 23 2 45 -19
43) Hierarchical clustering with heatmaps and dendrograms
clustergram
44) Save a matrix/variables to a tab delimited file
dlmwrite('output_tabdel.txt',out_array,'delimiter','\t')
45) gca to get current axis, see also axes and get() and set() commands
46) run unix command within matlab
unix('ls -ltr')
47) Alternative to using strcat to join strings (just make an array)
unix_command_3 = ['paste temp_' date '.txt ' temp_output_file ' >> ' final_output_file ]
unix(unix_command_3)
48) Method to find sum of the number that are significant (say FDR < 0.05)
output_fdr = mafdr(PValues);
size(find(output_fdr < 0.05),2)
% OR
output_fdr = mafdr(PValues);
iNum_signif = output_fdr < 0.05;
sum(iNum_signif)
49) Find names of files in folder/directory (inspired by a solution by Shannon Nicley Demlow) using dir command
name_files = dir;
num_files = length(name_files)
for iCount = 1:num_files
name_files(iCount).name
end
50) Save figure using saveas
saveas(gcf, 'figure.tiff', 'tiffn')
51) Generate linearly spaced vectors using linspace
linspace(1,100,10) # generate 10 points between 1 to 100
ans =
1 12 23 34 45 56 67 78 89 100
52) Solve PDEs
Use pdepe (that solves initial boundary value problems for parabolic-elliptic PDEs in 1 dimension using finite elements)
See file pdex1.m for details (edit pdex1.m)
Also can use pdetool (GUI)
53) Use format long to show numbers in long format
format long
54) Show all variables in workspace (useful when you dont have a local installation of matlab)
who
55) Save workspace variables to mat file
% save(filename)
save(sprintf('mdsine_summary_output_%s.mat',date))
56) Excellent collection of matlab functions (submission on Matlab Central)
57) MATLAB function to do LASSO (from the documentation page)
X = randn(100,5)
r = [0;2;0;-3;0] % only two nonzero coefficients
Y = X*r + randn(100,1)*.1 % small added noise
%%Construct the default lasso fit.
B = lasso(X,Y)
58) Usage of subplot command
% first two parameters are like array indices
figID = figure;
subplot(2,3,1)
hist(w_vector_array(iBurnIn+1:end,1))
hold on
subplot(2,3,2)
hist(w_vector_array(iBurnIn+1:end,2))
hold on
subplot(2,3,3)
hist(w_vector_array(iBurnIn+1:end,3))
hold on
subplot(2,3,4)
hist(w_vector_array(iBurnIn+1:end,4))
hold on
subplot(2,3,[5 6])
hist(w_vector_array(iBurnIn+1:end,5))
hold off
59) Having inline LaTeX commands in matlab code
%% do Bayesian regression
% w is vector of regressors
% P(w|D) ~ N(w| mu, lambda)
% mu = a * lambda^(-1) * A{transpose} * y
% lambda = a * A{transpose} * A + b*I
% $P(w|D) \sim N(w| \mu, \lambda)$
% $\mu = a * \lambda^{-1} * A^{T} * y$
% $\lambda = a * A^{T} * A + b*I$
60) Poisson probability density function
%poisspdf(x,lambda)
poisspdf(13,2)
lambda = 10;
poissrnd(lambda)
61) Binomial probability density function
adapted from matlab website
A Quality Assurance inspector tests 200 circuit boards a day. If 2% of the boards have defects, what is the probability that the inspector will find no defective boards on any given day?
binopdf(0,200,0.02)
ans = 0.0176
What is the most likely number of defective boards the inspector will find?
defects=0:200;
y = binopdf(defects,200,.02);
[x,i]=max(y);
defects(i)
ans = 4
rng default; % for reproducibility
r = binornd(100,0.9)
[phat, pci] = binofit(r,100)
binornd(100,0.02)
62) Persistent variables: variables that are local to the function but persistent between function calls
persistent X, Y, Z
63) Using profiler (from MATLAB documentation)
profile on
plot(magic(35))
profile viewer
p = profile('info');
profsave(p,'profile_results')
64) Different indexing schemes in MATLAB and co-distributed arrays (while working with parallel workers)
65) Using varargin and nargin to have variable number of arguments to functions (from MATLAB documentation)
% nargin stores number of arguments
function c = addme(a,b)
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end
% varargin stores function arguments
function varlist(varargin)
fprintf('Number of arguments: %d\n',nargin)
celldisp(varargin)
66) Tutorials on MATLAB parallel computing and GPU computing (link) and running MATLAB code on a cluster (link)
67) PCA plot in matlab
mapcaplot
68) SVM in matlab
svmtrain
svmclassify
69) Read phylogenetic tree
phytreeread
67) Machine learning with MATLAB (code) (webinar)
68) Cross-validation (machine learning) in matlab
cvpartition (create a partition)
crossvalind (generate indices) (also see SVM classifier here)
69) Pattern recognition with neural network
patternnet
Example (from mathworks documentation page)
[x,t] = iris_dataset;
net = patternnet(10);
net = train(net,x,t);
view(net)
y = net(x);
perf = perform(net,t,y);
classes = vec2ind(y);
70) Train neural network (machine learning)
train
71) Generate ROC curve (machine learning)
perfcurve
72) Confusion matrix (machine learning)
confusionmat
73) Discriminant analysis (machine learning)
classify
74) Biograph object
biograph
Example -
g = biograph(CMatrix)
view(g);
%% save visualization (from link)
gui_g = biograph.bggui(g);
f = figure;
copyobj(gui_g.biograph.hgAxes,f);
f = get(gui_g.biograph.hgAxes, 'Parent');
print(f, '-dpdf', ['network_visualization_' date '.pdf' ])
75) Draw from inverse Gaussian distribution or any other
pd = makedist('InverseGaussian','mu',mu,'lambda',lambda);
r = random(pd)
76) Basic code to simulate gamma distribution
function gamma_test()
alpha_shape = 10;%0.1
scale = 0.5
beta_rate = 1/scale
for iCount=1:1000
samples(iCount) = gamrnd(alpha_shape,beta_rate);
end
hist(samples,100)
disp('mean')
alpha_shape*scale
disp('variance')
alpha_shape*scale^2
77) Basic code to simulate negative binomial distribution
p = 0.1;
r = 10;
for iCount=1:1000
%% RND = nbinrnd(R,P) is a matrix of random numbers chosen from a negative binomial distribution
%% with corresponding number of successes, R and probability of success in a single trial
samples(iCount) = nbinrnd(r,p);
end
figID_2 = figure
hist(samples,100)
print(figID_2, '-dpdf', sprintf('nbin_testsamples_2_%s.pdf', date));
disp('mean')
p*r/(1-p)
disp('variance')
p*r/((1-p)^2)
78) Function to debug matlab programs
keyboard (link)
% can examine all workspace variables, etc
% return to continue execution, dbquit to exit
79) Check if variable has infinity
isinf()
80) Wishart distribution
Sigma = [1 .5; .5 2]; df = 10; S1 = wishrnd(Sigma,df)/df
S1 = 1.7959 0.64107 0.64107 1.5496
df = 1000; S2 = wishrnd(Sigma,df)/df
S2 = 0.9842 0.50158 0.50158 2.1682
81) Pass control to next iteration of for or while loop
continue
82) Kalman filters for object tracking
83) Parameterizing using anonymous functions (how to pass additional parameters to MATLAB functions)
84) Finding peaks in signals and time series data
% [pks,locs] = findpeaks(data)
Y = [ 1 2 1.1 3.4 5.6 1.9 0]
[pks,locs] = findpeaks(Y)
>
pks =
2.0000 5.6000
locs =
2 5
85) Successive differences of elements in a vector (diff)
A = [ 1 2 7 9 14]
diff(A)
ans =
1 5 2 5
86) Exception handling
try
<some statement>
catch
<error handling> % OR continue OR disp('error ignored')
end
87) Fast Fourier Transform (fft)
88) Bar plot with different text labels (from MATLABCentral)
fruit = [2 5 6 7]
bar(fruit)
set(gca,'XTickLabel',{'apples', 'oranges', 'strawberries', 'pears'})
89) Fitting generalized linear models (glmfit)
% Example (adapted from MATLAB documentation)
load fisheriris
X = meas(51:end,:);
y = strcmp('versicolor',species(51:end));
b = glmfit(X,y,'binomial','link','logit')
90) LASSO for generalized linear model (lassoglm)
% Also see this link
% Example (adapted from MATLAB documentation)
load fisheriris
X = meas(51:end,:);
y = strcmp('versicolor',species(51:end));
[B FitInfo] = lassoglm(X,y,'binomial','CV',10)
[B FitInfo] = lassoglm(X,y,'binomial')
lassoPlot(B,FitInfo,'PlotType','CV'); saveas(gcf,'lassplot_1.eps', 'psc2')
lassoPlot(B,FitInfo,'PlotType','Lambda','XScale','log'); saveas(gcf,'lassplot_2.eps', 'psc2')
91) Mapping functions in MATLAB (adapted from link)
% California map axes
figure; ax = usamap('california');
setm(ax, 'FFaceColor', [.5 .7 .9])
title('California map')
% read shapefile of US states with names and locations
states = geoshape(shaperead('usastatehi.shp', 'UseGeoCoords', true));
% display map
geoshow(states, 'Parent',ax)
lat = 37.773972
lon = -122.431297
linem(lat, lon, 'LineStyle','none', 'LineWidth',2, 'Color','r', ...
'Marker','x', 'MarkerSize',10)
saveas(gcf,'san_francisco.eps', 'psc2')
92) Remove duplicates and elements in another array (both arrays have a one-to-one correspondence) (using unique)
% DOES NOT WORK
% t has duplicates and V is another vector with one-to-one correspondence
temp_mat = [t; V];
a = unique(temp_mat,'rows');
t_mod = a(:,1);
V_mod = a(:,2);
% interpolate
virus_vector = interp1(t_mod, V_mod, [2 4 6],'spline')
disp('SSR WT')
% calculate SSR
sum((virus_vector' - fileptr_wt.data(:,2)).^2)
93) matlabpool replaced by paropen and delete (link for function to override)
94) Histogram colour by condition
% get metagene score and label into one matrix
p = [metagene_raw_log_score, Y==1];
% find index of responders and non-responders
idx = (p(:,2) == 1);
idx2 = (p(:,2) == 0);
% filter nad get separately metagene scores for resonders and non-responders
p_nonresponder = p(idx);
p_responder = p(idx2);
figure;
h1 = histogram(p_responder);
hold on;
h2 = histogram(p_nonresponder);
legend('IFX responder','IFX non-responder');
xlabel('Metagene score'); ylabel('Frequency'); title('Distribution of metagene score');
hold off
95) How to add matlab to PATH variable
If MATLAB is installed on ~/MATLAB/bin
then at UNIX command prompt
export PATH=$PATH:~/MATLAB/bin
96) Example to perform deep learning text classification in MATLAB (link)