Friday, March 20, 2015

[vim] auto complete matlab flow control [for, if, while] with indentation in vim

Okay, it turns out just combining some keys is good enough :(

:inoremap <c-n><c-n> <esc>yyp^d$a
:inoremap <c-c><c-c> <esc>yyp^d$aend<esc>kyyp^d$a
 
hit ctrl-c twice (holding ctrl) in the edit mode , use ctrl-n twice to go next line

------------------------------------------------------------------- no need something huge --------------------------
"=============================================================================
" matlabFlowComplete.vim v0.0
" Author: Xianmin Hu <xianmin.hu@gmail.com>
" http://scriptdemo.blogspot.com
" Last Change: 19-Mar-2015.
"=============================================================================
"
"key cc : to complete for, if and while flow
"key nn : go to next line with proper indentation

:function! CompleteMatlabFlow()
" complete for, while and if flow control with proper indentation
: let isValidForWhileIf=0
: let tmpline=substitute(getline(".")," \\+"," ","g")
: let tmpline=substitute(tmpline," \\+$","","g")
: call setline(".",tmpline)
: let tmpline=substitute(tmpline,"^ \\+","","g")
: let clinesp=split(tmpline," ")
: unlet tmpline
: execute "normal! o"
: execute "normal! kk^"
: if len(clinesp) > 1
:    if clinesp[0] == "for" && len(clinesp)>2
:       let isValidForWhileIf=1
:       if len(clinesp)==3
:          let newcline="for " . clinesp[1] . " = " . clinesp[2] . ":1:" . clinesp[2]
:       elseif len(clinesp)==4
:         if clinesp[2]<clinesp[3]
:            let newcline=clinesp[0] . " " . clinesp[1] . " = " . clinesp[2] . ":" . clinesp[3]
:         else
:           let newcline=clinesp[0] . " " . clinesp[1] . " = " . clinesp[2] . ":-1:" . clinesp[3]
:        endif
:      elseif len(clinesp)>=5
:       let newcline=clinesp[0] . " " . clinesp[1] . " = " . clinesp[2] . ":" . clinesp[3] . ":" . clinesp[4]
:      endif
:      let cpos = col(".")
:      let preline=split(getline(".")," ")
:      if len(preline) > 0
:         if preline[0] == "for"
:            let cpos += 4
:         elseif preline[0] == "while"
:            let cpos += 6
:         elseif preline[0] == "if"
:            let cpos += 3
:         endif
:      endif
:      while cpos > 1
:               let newcline = " " . newcline
:               let cpos -= 1
:       endwhile
:       execute "normal! j"
:       call setline(".",newcline)
:       execute "normal! yyp"
:       execute "normal! ^d$"
:       call setline(".",getline(".") . "end")
:       execute "normal! jdd"
:       execute "normal! kyykpd$i "
:       unlet newcline
:       unlet cpos
:    endif
"
:    if (clinesp[0] == "if" || clinesp[0] == "while") && len(clinesp)>1
:       let isValidForWhileIf=1
:       let cpos = col(".")
:       let preline=split(getline(".")," ")
:       if len(preline) > 0
:          if preline[0] == "for"
:             let cpos += 4
:          elseif preline[0] == "while"
:             let cpos += 6
:          elseif preline[0] == "if"
:             let cpos += 3
:          endif
:       endif
:       let padStr=""
:       while cpos > 1
:           let padStr = " " . padStr
:           let cpos -= 1
:      endwhile
:      execute "normal! j^0d^"
:      call setline(".", padStr . getline("."))
:      execute "normal! yyp^d$"
:      call setline(".",getline(".") . "end")
:      execute "normal! jdd"
:      execute "normal! kyykpd$i "
:      unlet padStr
:      unlet cpos
:   endif
:   unlet clinesp
: endif
: if isValidForWhileIf < 1
:    execute "normal! u"
:    execute "normal! $"
: endif
: unlet isValidForWhileIf
:endfunction

:function! GoMatlabNext()
" go next line and use same indent from previous line
: execute "normal! yyp"
: execute "normal! ^d$a"
:endfunction

:nmap cc :call CompleteMatlabFlow()<CR>a
:nmap nn :call GoMatlabNext()<CR>a
Example:
1) type "for a 1 4", then run cc in normal mode, ==>
for a = 1:4

end
2) type "for a 4 1", then run cc in normal mode, ==>
for a = 4:-1:4

end
3) type "for a 2 4 12", then run cc in normal mode, ==>
for a = 2:4:12

end
4) type "while a =4", then run cc in normal mode, ==>
while a=4

end

5) auto-indent
if you have"
%==============
if isLoop==1
for n loopStart loopStep loopEnd (run cc in normal mode)
end

it will result in:
%==============
if isLoop==1
   for n = loopStart:loopStep:loopEnd
         
   end
end

Friday, March 13, 2015

[matlab] relocate an object in the figure window

function movePosition(myh,myfrac,opt)
% move an object to a new location relative to current axes
% usage:
%      movePosition(obj-handle,fraction,opt)
%             opt: 'x' ==> x-coordiante is given in fraction of xlim
%                    'y' ==> y-coordiante is given in fraction of ylim
%                  'xy' ==> both x,y-coordiante is given in fraction
%                                (could be a 2-element vector)
% http://scriptdemo.blogspot.ca

if nargin~=3
   help movePosition
   return
end
if numel(myh)>1
   for nh=1:numel(myh)
       movePosition(myh(nh),myfrac,opt);
   end
   return
end
if ~ishandle(myh)
   error('need a valid object handle')
end

oriPos=get(myh,'position');
if isempty(oriPos)
    error('no position attribute is available')
end
if isnumeric(opt)
   oriPos(1)=myfrac;
   oriPos(2)=opt;
else
   switch lower(opt)
    case {'x'}
        cXLim=get(gca,'xlim');
        oriPos(1)=oriPos(1)+myfrac*(cXLim(2)-cXLim(1));
    case {'y'}
        cYLim=get(gca,'ylim');
        oriPos(2)=oriPos(2)+myfrac*(cYLim(2)-cYLim(1));
    case {'xy'}
        if numel(myfrac)==1
            myfrac=[myfrac myfrac];
        end
        cXLim=get(gca,'xlim');
        oriPos(1)=oriPos(1)+myfrac(1)*(cXLim(2)-cXLim(1));
        cYLim=get(gca,'ylim');
        oriPos(2)=oriPos(2)+myfrac(2)*(cYLim(2)-cYLim(1));
    otherwise
        error(['unknown opt: ',opt])
   end
end
set(myh,'position',oriPos);

[matlab] show available tags

function showtags(figH)
% to show all the tags in figure(s)
% usage:
%        showtags([figure_handles])
% e.g.,
%        showtags(gcf)
% http://scriptdemo.blogspot.ca

if nargin==1
   availableTag=unique(get(findobj(figH),'tag'));
   availableTagC=unique(get(findobj(figH),'Tag'));
else
   availableTag=unique(get(findobj(),'tag'));
   availableTagC=unique(get(findobj(),'Tag'));
end
if sum(~cellfun('isempty',availableTag))~=0
    disp('Available tags: ')
    disp(availableTag)
end
if sum(~cellfun('isempty',availableTagC))~=0
    disp('Available Tags: ')
    disp(availableTagC)
end

Wednesday, August 6, 2014

[Bash] sum numbers in an array

#!/bin/bash
# sum all/part the numbers in an array using bc
# usage:
#           mysum number-array [index0 index1]
#           Note: the index starts from 1
# e.g.,
#      myA=(34 23 32.5 33.2 25)
#      mysum "${myA[*]}" ==> 147.7
#      mysum "${myA[*]}" 1 2 ==> 57
#      mysum "${myA[*]}" 2 4 ==> 88.7
#      mysum "12 23 12" ==> 47
#
# http://scriptdemo.blogspot.com

isDebug=0
if [ $# -eq 0 ]; then
   sed -n '3,8p' `which mysum`
   exit
else
  myA=($1)
  [ ${isDebug} -eq 1 ] && echo ${myA[*]}
  [ ${isDebug} -eq 1 ] && echo "narg: $#"
  if [ $# -eq 1 ]; then
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]} | sed 's/\ /+/g' | bc -l`"
     fi
  elif [ $# -eq 2 ]; then
     ind0=`expr $2 - 1`
     nC=`expr ${#myA[*]} - ${ind0}`
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     fi
  elif [ $# -eq 3 ]; then
     ind0=`expr $2 - 1`
     nC=`expr $3 - ${ind0}`
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     fi
  fi

Wednesday, March 12, 2014

[Matlab] make the t-s diagram with a third field shown in color

function [hc]=theta_sdiag(theta,s,varargin)
% make the t-s plot given temperature and salinity data with ability to show a third field (e.g., density, depth) in color
% need sw_dens.m from the seawater package
% usage:
%         hc=theta_sdiag(theta,s,varargin)
%             varargin:
%               ['color',value] : if value=1, the density will be shown in color;
%                                        otherwise value should be some filed (e.g., depth) with same size as theta/s
%         ['trange',Trange] : the range of temperature shown on the plot (ylim)
%         ['srange',Srange] : the range of salinity shown on the plot (xlim)
%  ['markersize',size-of-marker] : as it tells, the marker size, check scatter for its definition
%     ['caxis',color-range] : the range of the third field shown in color
% e.g.,
%       hc=theta_sdiag(t,s,'color',dep,'caxis',[10 500],'trange',[-2 10],'srange',[31.5 34.8]);

% history:
%
% April 2009: original code by Vihang bhatt
%                    http://www.mathworks.com/matlabcentral/fileexchange/23796-t-s-diagram/content/theta_sdiag.m
% March 2014: enable to show a thrid field in color and more other options by xianmin (xianmin@ualberta.ca)
%                    http://scriptdemo.blogspot.com

if nargin<2
   help theta_sdiag
   return
end

isColor=0;
markerS=16;
if nargin>3
    while(size(varargin,2)>0)
        switch lower(varargin{1})
            case {'iscolor','color'}
                if numel(varargin{2})~=1
                    colorVar=varargin{2};
                    isColor=2;
                else
                    isColor=varargin{2};
                    if isColor==2
                        error('isColor should not equal 2 if no variable specified for the scatter color')
                    end
                end
                varargin(1:2)=[];
            case {'dt','deltat'}
                deltaT=varargin{2};varargin(1:2)=[];
            case {'ds','deltas'}
                deltaS=varargin{2};varargin(1:2)=[];
            case {'tmin','mint'}
                thetamin=varargin{2};varargin(1:2)=[];
            case {'tmax','maxt'}
                thetamax=varargin{2};varargin(1:2)=[];
            case {'trange','tlimit','ylim','tlim'}
                tRange=varargin{2}; thetamax=tRange(2); thetamin=tRange(1); varargin(1:2)=[]; clear tRange
            case {'smin','mins'}
                smin=varargin{2};varargin(1:2)=[];
            case {'smax','maxs'}
                smax=varargin{2};varargin(1:2)=[];
            case {'srange','slimit','xlim','slim'}
                sRange=varargin{2}; smax=sRange(2); smin=sRange(1); varargin(1:2)=[]; clear sRange
            case {'markersize'}
                markerS=varargin{2};varargin(1:2)=[];
            case {'caxis','mycaxis'}
                myCAXIS=varargin{2};varargin(1:2)=[];
            otherwise
        end
    end

end

theta=theta(:);
s=s(:);
if ~exist('smin','var'), smin=min(s)-0.01.*min(s); end
if ~exist('smax','var'), smax=max(s)+0.01.*max(s); end
if ~exist('thetamin','var'), thetamin=min(theta)-0.1*max(theta); end
if ~exist('thetamax','var'), thetamax=max(theta)+0.1*max(theta); end
if ~exist('deltaS','var'), deltaS=0.05; end
if ~exist('deltaT','var'), deltaT=0.25; end

xdim=round((smax-smin)/deltaS+1);
ydim=round((thetamax-thetamin)/deltaT+1);
dens=zeros(ydim,xdim);
thetai=((1:ydim)-1)*deltaT+thetamin;
si=((1:xdim)-1)*deltaS+smin;

for j=1:ydim
    for i=1:xdim
        dens(j,i)=sw_dens(si(i),thetai(j),0);
    end
end

dens=dens-1000;
[c,h]=contour(si,thetai,dens,'k');
clabel(c,h,'LabelSpacing',1000);
xlabel('Salinity','FontWeight','bold','FontSize',12,'fontname','Nimbus Sans L')
ylabel('Theta (^oC)','FontWeight','bold','FontSize',12,'fontname','Nimbus Sans L')
set(gca,'fontname','Nimbus Sans L')

%% plotting scatter plot of theta and s;
hold on;

if isColor==1
   mydens=sw_dens(s,theta,0)-1000;
   hc=scatter(s,theta,markerS,mydens,'o','fill');
   set(hc,'markeredgecolor','none');
elseif isColor==2 % use the depth as color
   if ~exist('myCAXIS','var')
       myCAXIS=[nanmin(colorVar(:)) nanmax(colorVar(:))];
   end
   caxis(myCAXIS);
   hc=scatter(s,theta,markerS,colorVar(:),'o','fill');
   set(hc,'markeredgecolor','none');
else
   hc=scatter(s,theta,'.');
end

if nargout==0
   clear hc
end

Thursday, September 5, 2013

[MATLAB] read the byte-binary ice concentration data from NSIDC

function myice=readgsfcice(fname,fnamemask)
% read the binary ice concentration data from gsfc
% similar to the fortran version here
% data description:
%     http://nsidc.org/data/docs/daac/nsidc0051_gsfc_seaice.gd.html
% data :
%     ftp://sidads.colorado.edu/pub/DATASETS/nsidc0051_gsfc_nasateam_seaice/final-gsfc/north/
% mask :
%     ftp://sidads.colorado.edu/pub/DATASETS/brightness-temperatures/polar-stereo/tools/masks/
% usage:
%     myice=readgsfcice(ice_filename, mask_filename)
%     myice: ranging 0 to 1, land value is nan if the mask file is specified
%     http://scriptdemo.blogspot.com
 

isMask=1;
if nargin<1
   help readgsfcice
   return
elseif nargin==2
   if ~exist(fnamemask,'file')
      disp(['mask file not found: ',fnamemask])
      isMask=0;
   end
end
if nargin==1
   isMask=0;
end
if ~exist(fname,'file')
   error(['file not found: ',fname])
end

% read the data
fid=fopen(fname,'r');
% read the header
myheader=(char(fread(fid,300,'uchar')))';
nrow=str2num(myheader(13:18));
ncol=str2num(myheader(7:12));
myscale=str2num(myheader(121:126));
%read data block
myice=fread(fid,'uint8');
fclose(fid);

% read the mask file
if isMask==1
   fid=fopen(fnamemask,'r');
   mymask=fread(fid,'uint8');
   fclose(fid);
   myice(mymask==1)=nan;
end
myice=reshape(myice,ncol,nrow)/myscale;

[Fortran] dump the byte-binary ice concentration data from NSIDC

! @ http://scriptdemo.blogspot.com
! tested on  Linux 2.6.32.26-175.fc12.i686
! convert the byte-binary ice-concentration data file from NSIDC to ascii text format
! data description:
!         http://nsidc.org/data/docs/daac/nsidc0051_gsfc_seaice.gd.html
! data download:
!         ftp://sidads.colorado.edu/pub/DATASETS/nsidc0051_gsfc_nasateam_seaice/final-gsfc/

program dumpGSFCIce
integer, parameter                    :: lenHeader=300
character(len=40)                     :: fname, myfmt, txtfname
character(len=lenHeader)          :: header
integer                                    :: numLen, j,fid,npos, nrow, ncol, getnum, myscale,nlen
character(len=1),allocatable,dimension(:)    :: dblock
integer, allocatable,dimension(:)                 :: myice
logical                                                      :: isDebug=.false.

write(*,*) 'input the bin file name to open:'
read(*,'(a)') fname
write(*,*) 'input the txt file name to save:'
read(*,'(a)') txtfname

fid=7
open(fid,file=trim(fname),form='unformatted',access='direct',recl=4*lenHeader)
read(fid,rec=1) header
close(fid)

ncol=getnum(header(7:12))
nrow=getnum(header(13:18))
myscale=getnum(header(121:126))
if (isDebug) then
   write(*,*) '------------------ begin file header info ------------------------'
   write(*,'(a20,a)') ' file name: ', header(127:150)
   write(*,'(a20,a)') ' image title: ', header(151:230)
   write(*,'(a20,a)') ' year: ', header(103:108)
   write(*,'(a20,a)') ' julian day: ', header(109:114)
   write(*,'(a20,a)') ' scale factor: ', header(121:126)
   write(*,'(a20,a)') ' instrument: ', header(55:60)
   write(*,'(a20,a)') ' other info: ', header(231:300)
   write(*,'(a20,i0)')' num of col: ', ncol
   write(*,'(a20,i0)')' num of row: ', nrow
   write(*,'(a20,i0)')' scale factor: ', myscale
   write(*,*) '------------------ end file header info ------------------------'
endif

! declaration
nlen=ncol*nrow
numLen=lenHeader+nlen
allocate(dblock(numLen))
allocate(myice(nlen))

open(fid,file=trim(fname),form='unformatted',access='direct',recl=4*numLen)
read(fid,rec=1) dblock(:)
close(fid)

! convert the 1-byte char to integer
npos=lenHeader
Do j=1,nlen
     npos=npos+1
     myice(j)=ichar(dblock(npos))
Enddo
deallocate(dblock)

! write the file
write(myfmt,'(a,i0,a)') '(',ncol,'i4)'
open(fid,file=trim(txtfname),form='formatted')
write(fid,trim(myfmt)) myice
close(fid)
deallocate(myice)
end program dumpGSFCIce

function getnum(instr)
character(len=6), intent(in) :: instr
character(len=6) :: newstr
integer :: getnum
integer :: i, n
logical :: isnum
n=0
Do i=1,6
     if (isnum(instr(i:i))) then
        n=n+1
        newstr(n:n)=instr(i:i)
     endif
Enddo

if (n==0) then
   getnum=0
else
   read(newstr(1:n),*) getnum
endif
end function getnum

function isnum(myc)
character(len=1), intent(in) :: myc
logical :: isnum
isnum=.false.
if ( (ichar(myc).ge.ichar('0')) .and. (ichar(myc).le.ichar('9'))) isnum=.true.
end function isnum

Wednesday, June 19, 2013

[Bash] text to html using vim built-in function TOhtml

#!/bin/bash
# convert a text file to html using vim built-in function TOhtml
# usage:
#            toHTML text-files
# http://scriptdemo.blogspot.com

if [ $# -eq 0 ]; then
   sed -n '3,4p' `which toHTML`
   exit
else
   for mytxt in $*
   do
      if [ -e ${mytxt} ]; then
         vim -c 'syntax on|TOhtml' -c 'wq|q!' ${mytxt}
      else
         echo "${mytxt} is not found"
      fi
   done
fi

Friday, May 3, 2013

[Matlab] remove the water bodies in a m_map figure

function m_nolakes(lakeColor)
% delete the water bodies patches in figures created by m_map
%           default lakeColor is white ([1 1 1])
% usage:
%           m_nolakes(lakeColor)
%           http://scriptdemo.blogspot.com

if nargin==0
   lakeColor=[1 1 1];
elseif nargin~=1
   help m_nolakes
   return
end

gshhstypes={'c','l','i','h','f'};
for nt=1:numel(gshhstypes)
    eval(['hw=findobj(gcf,''type'',''patch'',''tag'',''m_gshhs_',gshhstypes{nt},''',''facecolor'',lakeColor);']);
    if ~isempty(hw)
       delete(hw);
    end
end
hw=findobj(gcf,'type','patch','tag','m_coast','facecolor',lakeColor);
if ~isempty(hw)
   delete(hw);
end

Sunday, April 7, 2013

[Bash] extractBib: extract bib items from a source bibtex database for a given tex file

#!/bin/bash
# extract bib items from a source bibtex database for a given tex file
# usage:
#          extractBib tex-file bibtex-database output-bibtex-file
# e.g.,
#          extractBib mypaper.tex mybibtexdatabase.bib mypaper.bib
# http://scriptdemo.blogspot.com

function getkeys()
{
   texfile=$1
   mykeys=`grep "cite.*{.*}" ${texfile} | sed -e 's/\ //g' | awk '{for (i=1; i<=NF;i++) {if ($i ~ /cite/) {print $i}}}' | sed -e 's/\}/\n/g' | awk -F\{ '{print $2}' | sed -e 's/\,/\n/g' | sed '/^[\ ]*[\ ]*$/d' | sort | uniq | sed '/^\\\\/d' | sed '/:/d'` 
   echo ${mykeys}
}

if [ $# -eq 3 ]; then
   texfile=$1; bibfile=$2; outfile=$3
elif [ $# -eq 2 ]; then
   texfile=$1; bibfile=$2; outfile="extractbib_"$1
else
   echo "usage:"
   echo "          extractBib tex-file bibtex-database output-bibtex-file"
   exit
fi

# make sure no overwrite
[ -e ${outfile} ] && echo "${outfile} exists alreay! exit" && exit

allkeys=`getkeys ${texfile}`
if [ ${#allkeys[*]} -ne 0 ]; then
   touch ${outfile}
   for eachkey in ${allkeys[*]}
   do
       #echo ${eachkey}
       sed -ne "/${eachkey}/,/^[\ ]*\}$/p" ${bibfile} >> ${outfile}
   done
fi

Thursday, February 14, 2013

[Matlab] show a normal random heart

% Just for fun, not really useful....
% @ http://scriptdemo.blogspot.com 
clear; close all;
r=0.618; n=10000; re=sqrt(1-r*r);
x=normrnd(0,1,n,1);
y=x*r+normrnd(0,1,n,1)*re;y(x<0)=-y(x<0);
plot(x,y,'o','markerEdgeColor',[1 0 1],'markerFaceColor','none');
axis equal tight off;
set(gcf,'MenuBar','none','color','w')

ShowCalendar