p MATLAB scripts Home

[ PSFC | alta ]

MATLAB Scripts

Some of these Matlab files may be very useful for you, so just click on the *.m-file link and save the file in your MATLAB6p1/work folder or MATLABr11/work folder (or some other one depending on your Matlab version). More advanced users can put the files anywhere, of course. I've tested them all on Matlab 6.1, version 12, so they may not be entirely backwards compatable, although Matlab is usually pretty good about that.

  • Posted 10/28/04

    GKLMovie.m This script plots the nonlinear electron and efficiency evolution for a gyrotron cavity with a prebunched beam, so it's applicable to the final cavity of a gyroklystron, or to a gyrotron (if the bunching parameter q=0). Read the top of the file so you understand what's going on.

    Requires: GKLceta2.m and WaitbarBandColor.m


  • Posted 10/28/04R

    PicPuzzle.m This clever program takes a folder of images (the more the better, but I used around 500) and an input "target" image, and attempts to form a vague, artistic collage of the target image using small versions of the input images. It works pretty well, but resizing the many images takes a long time, so I recommend you start with small images no larger than 0.1 MegaPixels, while I used a 14MP target image to retain the large size (the sample at right was downsize 25%). Pretty cool, but also a little scary! Requires imageCrop.m, WaitbarRandColor.m, and sec2time.m.

  • Posted 10/28/04

    WaitbarRandColor.m This cute script simply changes the color of your waitbar to a random color everytime you call it and also moves the position of the waitbar to the lower left side of your screen instead of smack in the middle.
    NOTE: For some reason, you cannot use the waitbar command on the default Windows XP theme -- switch it to windows classic and waitbar will work. Maybe there's just a problem with the configuration on my computer...

  • Posted 8/6/04F

    BesselJPrimeRoots.m This function is extremely useful for those who work with cylindrical waveguide systems. MATLAB has the BesselJ function and borrows the 'BesselJZeros' command from MAPLE, but there's no way to find the zeros of, for example, J'_1(nu_mp)=0, which you need to find the Bessel maxima in a cylindrical waveguide. The inputs are the indicies (m,p) of the root you want and can be vectorized.


  • Posted 3/19/04

    Homestar.m This great script plays quotes from various characters from HomestarRunner.com . I wrote it because I wanted some way of signalling when a lengthy program run finished. What better way to end such a wait than with a hilarious quotes, like "No two people are not on fire." - Strong Bad, or "I'm takin' a leak!" - Coach Z, or "Is there ice cream yet?" - Homestar. You'll need the homestar_quotes.zip (715kB, updated 8/5/04) package, which contains 41 wav file quotes you can't download from the webpage. You'll have to change the "folder = ..." line in the homestar.m script to get it to work right for your configuration.

    Basically, the function has three modes: if you give it the argument 'who', it returns a list of available quotes. 'r' plays a random quote through the audio system, and N, which plays the N-th quote. Also, if the function is assigned arguments, it returns a vector of the quote data and the sample frequency.

    Watch for updated quotes packages containing more hilarious quotes! I tried to compile this function so it could be used as a stand-alone executable, but it gave me an error that the audio was not available, and I don't know how to fix that.


  • Posted 10/14/03

    image_deblur.m This short and not well written script does a sort of cookie-cutter image deconvolution. I was just amazed with how it took a tiny image, blew it up to 9 times the area, interpolated to smooth it (looked blurry) and then deblurred with incredible ability.

  • Posted 8/19/03

    TEmodes.m This program is useful for finding the bessel roots often needed for analyzing electromagnetic fields in cylindrical waveguides. The Transverse Electric (TE) modes specifically arise in gyrotron and gyroklystron research. There is extensive functionality built into this versatile code, which makes use of the 'varargin, nargin, varargout, nargout' function variables to extend its usefulness. The script requires nu_TE.txt in the same folder, which is a data file containing the first 335 TE mode roots to at least 5 significant figures.

    TMmodes.m is the conterpart for Transverse Magnetic electronmagnetic fields. It requires nu_TM.txt, which contains the first 502 modes, also to at least 5 significant figures.


  • Posted 8/12/03

    GKLmagnet3.m This program is very similar to GKLmagnet2.m (posted 7/23/03), but it includes the effects of (and 3-D plot of) a weaker 3rd magnet located far from the other two main coils (which are in a Helmholtz-like configuration). This 3rd coil, called a "gun-coil" due to its proximity to the electron gun, can allow the gun to be much closer to the uniform region provided the coil is strong enough, an advantage which reduces the detrimental effects of velocity spread in the electron beam. If this coil is too stong or too close to the uniform region, it adversely affects the uniformity. In my case, I was able to move the gun position from 53cm to 35cm using a 0.75T gun coil and only dropped a little in the uniformity: from 12.0cm to 11.3cm. Yeah, it's 300 lines, mostly making the figure look nice. Requires find_intersection.m.


  • Posted 8/9/03

    GKLcontour2.m This program computes contours showing efficiency, bunching parameter "q", detuning parameter "delta" and relative phase "psi" as functions of the normalized field "F" and normalized cavity length "mu" for the extraction (final) cavity of a Gyroklystron device. This cavity operates in a non-linear regime, so this script solves a non-linear differential equation using the function GKLceta2.m and the ode45 command, which is then optimized for q, psi and delta for the maximum efficiency (a 3-D optimization) for each value of F and mu using the fminsearch command. It can easily take a few hours to get decent resolution on these plots, so it's best to run it overnight. However, it's such a specialized program that no one will ever use it unless they want to see how to solve a differential equation in matlab and then optimize it. By the way, the differential equation is solved in parallel for a vector of initial conditions, usually about 300 in my case.

    Before I streamlined everything Matlab-style (vector and matrices), I first wrote it using for-loops ... errr, 7 of them, all nested! for-loops are terrible style for Matlab-- in fact, I found that instead of being Order(n^1) with a loop for my initial conditions, I found that it was more like O(n^0.3) for the vector of initial conditions! Great improvement for 300 conditions that can get recalculated a thousand times for a run!

    Because it takes so long to run, I implemented the waitbar command and a fancy algorithm for predicting the remaining run time, which is quite accurate after the program is about 33% done. Also requires sec2time.m to print the run time.

    A future modification may be to include the effects of velocity spread by changing the 'pin = 1' line in GKLceta2.m with a Gaussian random variable with non-zero standard deviation. This is not so simple, because each run would be different, but I don't know how else to do it, because the initial momentum (pin) probably should not be correlated with the uniformly distributed (deterministic) initial phases, theta_c.

  • Posted 8/9/03

    Constants.m This program loads many common constants used in different kinds of scientific work. These constants are the CODATA Internationally recommended values as of 1998. It includes many commonly used constants such as c = 299,792,458 m/s, epsilon_0, mu_0, electron mass, elementaery unit of charge, etc. You use the command run constants in your Matlab script near the top and it loads the values into the workspace, along with a structure containing their descriptions and units.


  • Posted 7/23/03

    GKLmagnet2.m Like GKLmagnet.m, this one computes the on-axis magnetic field strength for two coils, so it adds the ability to specify the coil separation. It also shows you visually if the uniformity specification is stretched too far, resulting in two small fields instead of one larger one. It sure does take a lot of code to make the plot look pretty like that. Wow, two coils really do produce a much longer flat field region.

  • Posted 7/23/03

    sec2time.m Converts seconds into a string of the form 0:00:00 corresponding to hrs:min:sec. It's very useful for commands like "toc" - just call it with something like disp(['Total time: '   sec2time(toc)]);


  • Posted 7/20/03

    DDLMS.m A Decision Directed Least Mean Square error adaptive filter for deciding how to assign received noisy, distorted bits to their original transmitted states. Uses the "In-phase" and "Quadrature" methodology in the complex plane as a model.


  • Posted 7/20/03

    LinearAdaptPredict.m A Linear Adaptive Predictor example taken fairly word for word out of a Matlab example on neural networks. It removes the noise from a signal by adaptively predicting the next output sample, thereby removing noise.


  • Posted 7/20/03

    LinearAdaptPredict2.m Another Linear Adaptive Predictor homework. This one is all hard coded (i.e., with for loops and other hand-generate kludge), and it generates something like 10 figures corresponding to 5 different cases or something. It shows the weights, error, original signal and filtered signal on one plot, as well as the frequency response and phase of the corresponding filter at different points in time (the filter changes in time to follw the signal, hence the term "adaptive").


  • Posted 7/20/03

    hw_convectiveInstability.m Plots the time growth of a convective instability and also the dispersion diagram. It was a homework problem for the 6.641 (Electromagnetics of Forces and Motion) grad course at MIT.


  • Posted 7/20/03

    hw_equipotential.m Plots the equipotential contours and electric field vectors as a solution to a quasistatics homework problem. Limited use, but a good illustration of how to plot the electric field vectors and equipotential contours in a quick easy way. It was a homework problem for the 6.641 (Electromagnetics of Forces and Motion) grad course at MIT.


  • Posted 7/20/03

    rebound.m Of limited use, but it was written to find the magnitude of the ripple in a clock signal which could cause false clock triggering. It's a lot easier for a human to locate the ripple points than a computer! Not very useful nor exciting.


  • Posted 7/20/03

    filterChebyExample.m Just plots frequency and phase response of a sample Chebyshev filter and plots the poles and zeros on the complex plane.


  • Posted 7/20/03

    animateDipole.m Animates the equipotential field lines of an electric dipole to illustrate how the equipotential contours vary in time. In my opinion, the program is very poorly documented, since I didn't write it.


  • Posted 7/15/03

    gyrotronRadiusTD.m This program was useful for gyrotron cavity profile plotting because you specify the taper angle and section distance of a multi-section cylindrical cavity. This program is easily interfaced to the 'CYLINDER' command to make a 3-D rendition of the profile.

    gyrotronRadiusTDM.m Does the same thing as gyrotronRadiusTD.m, but adds the ability to specify interpolated data points between sections rather than just the inflection points at the section boundaries. To make it more useful for simulators, you specifiy not the spacing between axial interpolation, but the number of mesh points per section.

    gyrotronRadiusRT.m Also similar to gyrotronRadiusTD.m, but you specify the final radius of each section and the taper angle for that section and it computes the section lengths. Returns [] for theta = 0 or if the radius is increasing but theta < 0.

    gyrotronRadiusRTM.m Same as above (gyrotronRadiusRT.m), but allows a mesh to be defined to interpolate a specified number of points between sections.


  • Posted 7/11/03
  • Updated 10/2/03 - includes image rotation.

    image_adjust.m This is a sort of replacement for those darn image enhancement programs that come with your Windows XP computer, but expire in 30 days, after they've become the default program to open all your pictures. Well, it's not that fancy, it just lets you adjust the Red, Green, and Blue levels additively and lets you "compress" the image by raising the image data to a small exponent, essentially increasing or decreasing the contrast. It's simple, but it gets the job done in the absence of Photoshop or other fancy programs.


  • Posted 7/11/03, updated 7/14/03

    GKLmagnet.m Finds the magnetic field along the Z-axis of a finite-length, non-zero thickness cylindrical superconducting magnet, assuming uniform current density (which is the case in any wound magnet) passing through the rectangular cross-section of the cylinder. Generates a nice 3-D plot of the cylinder with the magnetic field profile superimposed. I really like the floating grid in 3-D, so I'll try to fix that up and turn it into a function called "grid3d" or something.

    OptimalMagnet.m For a given minimum inner radius, maximum outer radius, minimum thickness and maximum length, this program finds an optimal set of radii and length to meet a user-specified constraint on length of uniform field and the tolerance of uniformity. It's pretty slick, but it written very kludgily with for-loops. Aaaagh, what repulsive programming for Matlab. For-loops are for C and Fortran. Yes, it definetely should be written in C, or at least compiled in Matlab into C using the MCC command. I ended up using for-loops because I couldn't figure out how to multiply numbers into a 4-D matrix. In retrospect, I probably should have made 4-D matrices with variations in orthogonal directions using the CAT command, then just dot-multiplied them. Oh well, the for-loops work too. It's a very useful program when used with GKLmagnet.m above, because you can just pick a data set and run it in GKLmagnet.m to check it.

    These versions only compute the field profile on the Z-axis, but a future version may actually show you a transparent 3-D field strength plot to show the cylindrical volumetric intensity. This would allow one to create plots for NMR magnets, where the intensity must be within a certain tolerance through a volume.


  • Posted 7/11/03

    gyroDispersionRelation.m Plots the dispersion relation for a cylindrical resonator, along with the operation resonance lines for a gyrotron Traveling Wave Tube (TWT), Backward Wave Oscillator (BWO), and Cyclotron Auto-Resonance Maser (CARM).


  • Posted 7/11/03

    PBG.m 3-D plot of a mesh of rods representing a 2-D Photonic Band Gap structure with a defect in the center to guide electromagnetic waves.


  • Posted 7/11/03

    find_intersection.m One of the most useful programs out there that does a very simple task: finding where two curves cross. While a very simple task for humans, it was one of the more difficult programs I'd written because of the discreteness of data in a computer. In math, you set y1(x) = y2(x), but when you have discrete data, you may not find a point where y1(nD) = y2(nD), n={integer}.


  • Posted 7/11/03

    webpic.m This great program is very useful if you take a lot of pictures with your digital camera but have a hard time deciding what to do with them. This program will take your originals and (1) give them new names to replace the DSCFJPEGXRQQQQ000001.JPG crap names that it gives them originally to names like "home1.jpg", "home2.jpg" etc., (2) it creates thumbnail images and finally (3) it puts the thumbnail images into a webpage. Clicking on the thumbnails brings up the full size image. It's very handy. Just make sure you save your originals in another folder incase something strange happens and they accidentally get erased. Honestly, I could spend a week carefully writing error catching codes and thinking of all possible things that could go wrong (like telling it to rename your images to the same name), but it's really not worth it. Just make the copies!

  • Posted 7/11/03

    address.m A rather handy program driven by my annoyance at always running out of space in my address books for people's information. These days, everyone has 3 email addresses, 6 phone numbers and 87 screen names. This program lets you put whatever fields you want into it (as long as you initialize it with everything you'll ever need) and only displays those fields that have information. It also lets you search for key words, people, etc., and organizes people based on their last name. It does have a fair amount of error catching to it, which is always a pain to implement. It's long as hell, like 350 lines or something. It was a bear to write, but I had fun.

  • Posted 7/11/03

    tune.m Uses the computer speakers to generate the standard E A D G B E needed to tune a guitar. I checked it with my guitar tuner and, sure enough, it does give the exact frequencies! You also need note.m and sumcos.m to make it work.

    bach.m Also uses note.m and sumcos.m. Generates the first minute of Bach's "Jesu Joy of Man's Desiring" in it's full electronic MATLAB glory. It was an assignment for a class. I don't write these things for fun every day. Okay so I did do 10 times more than I had to for the assignment.

    play_scale.m Just plays any major scale for whatever good that is. Again, you'll need note.m and sumcos.m.



  • Home