Friday, December 17, 2010

Visualize Julia Sets using Matlab

function myjulia(Zmax,c,N)
% Generate and visualize quadratic Julia Sets
% More information about Julia Sets can be found here:
% http://en.wikipedia.org/wiki/Julia_set
% this code is for the assignment of the "Introduction to Matlab" offered by MITOPENCOURSEWARE
% Coded by http://scriptdemo.blogspot.com

if (nargin==1)
   Ndemo=Zmax; clear Zmax
   switch Ndemo
   case {1}
       myjulia(1,-0.297491+i*0.641051,100);
       return;
   case {2}
       myjulia(0.35,-0.297491+i*0.641051,250);
       return;
   otherwise
      disp('Not defined demo type!')
      help myjulia;
      return
   end
elseif (nargin~=3)
   help myjulia;
   return
end

% generate the basic matrix
NM=500;
[Z,tmpy]=meshgrid(linspace(-Zmax,Zmax,NM),zeros(1,NM));
Z=Z+i*Z'; clear tmpy

% compute the escape velocity
myM=reshape(escapeVelocity(Z(:),c,N),NM,NM);

% visualize the results
imagesc(atan(0.1*myM)); figurenicer;axis xy;

function n=escapeVelocity(z0,c,N)
n=z0*0;
NLen=length(z0);
IndZ=1:length(z0);
IndZ=IndZ';
for ni=1:N
      IndLT=find(abs(z0)<2);
      IndGE=find(abs(z0)>=2);
      n(IndZ(IndGE))=ni;
      if (length(IndLT)>0)
         z0(IndLT)=z0(IndLT).*z0(IndLT)+c;
      end
      z0(IndGE)=[];
      IndZ(IndGE)=[];
end
if ~isempty(IndZ)
   n(IndZ)=N;
end
myjulia(2)

Generate a series of column names in R

#if you want a series of column names, e.g., col1,col2,col3, ...,
#you can use:
mydf<-data.frame(matrix(ncol=5,nrow=4))
colnames(mydf)<-c("col1","col2","col3","col4","col5")
#Well, it does work, but how about for 50 columns?
#A loop! Sounds great. Okay,
mydf<-data.frame(matrix(ncol=50,nrow=4))
for (n in 1:ncol(mydf))
{
      colnames(mydf)[n]<-paste("col",n,sep="")
}
#But again, it's as urgly as the textbook. Here we offer a much better solution:
colnames(mydf)<-paste(rep("col",ncol(mydf)),c(1:ncol(mydf)),sep="")
#Smart, eh? At least the nicer looking :)
#From http://scriptdemo.blogspot.com

Trim a string in R

# sub-functions
# Copyright: http://scriptdemo.blogspot.com
mytrim<-function(oristr)
{
     oristr<-sub("^ +","",oristr)
     oristr<-sub(" +$","",oristr)
     # or gsub("(^ +)|( +$)","",oristr)
     return(oristr)
}

ShowCalendar