Tuesday, August 14, 2007

Speed up matlab script

http://www-h.eng.cam.ac.uk/help/tpl/programs/Matlab/faster_scripts.html
It's useful for me

Matlab - faster scripts

Matlab is easy to use, but the easiest method might not be the fastest. Fortunately, some of the simpler ways to improve the speed of matlab programs are also amongst the most effective, leading to order-of-magnitude improvements.

Firstly, make sure you're not writing unnecessary code. Each new version of matlab has new functions that might be useful, and functions that have been made faster. Remember that some of matlab's commands are scripts and some are built-in functions which are going to be faster than anything you can write. Use the which command to find out whether or not a function is a script (cumsum for example, isn't).

Also make sure you're up to date with matlab's newer features: Some (like cells and structures) might make your code tidier but slower; others (like the newer visualisation routines) may speed up your code considerably.

Matlab 6.5 introduced the "JIT-Accelerator" which greatly speeds up some scripts with big simple "for" loops. If you have pre-2006 matlabs it might be worth use the profile routine to help you adapt your code to take advantage of it. See the JIT-Accelerator example. Newer matlabs don't show JIT information in the profile output.

Then go through this checklist of issues to consider

Matlab Routines

Some matlab routines are *.m files, others are compiled into matlab (built-in) and are much faster. Try to use built-ins where possible. Use type functionname to see if a function is a built-in.

Functions and Scripts

There are 2 sorts of M-files - functions and scripts. When you call an M-file function MATLAB parses it and stores it in memory, so that on subsequent calls it runs faster. The difference isn't much, but functions are better than scripts anyway - they make use of their own local variables and accept input arguments. Look up the function command to find out how to write functions.

You can convert a function into matlab's internal form yourself using the pcode command, but it's hardly worth it.

Matrix pre-allocation

Matlab has the ability to increase the size of a matrix on demand. If you know the maximum size of a matrix beforehand, it's worth creating the matrix with this size initially rather than making the matrix grow incrementally. Speed-up factors of 500 are possible using this method.

Sparse Arrays

Matlab has 2 ways of storing matrices - full and sparse. Full matrices store their all of their elements in a block of memory; sparse matrices keep a list of the non-zero elements. If matrices aren't dense, using sparse matrices saves memory and increases speed. If you save the following text as spdemo.m you can experiment with using different matrix sizes and densities. For example, spdemo(100,.1) compares multiplication for full and sparse matrices of size 100 by 100 and density .1.
function sp = spdemo(arg1, arg2)
% Comparison of sparse vs full matrices
if (nargin ~= 2)
error('Give order and density');
return
end
S = sprandn(arg1,arg1,arg2);
F = full(S);
% Compare speed.

t0=cputime;
B = S * S;
stime=cputime-t0;

t0=cputime;
C = F * F;
ftime=cputime-t0;

sprintf('Order %d matrix, density %f: Full=%f, Sparse=%f', arg1, ...
arg2, ftime, stime)

Structures and Arrays

Structures of arrays are faster than arrays of structures.

Note that if you're processing a 2D array, it's faster to scan down the columns than along the rows.

Profiling

Before you start spending a lot of time on optimising it's useful to find out where the main bottlenecks are. The profile command can do this for you, providing text or graphical output. For example, this is how you could profile spdemo.m
  profile on 
spdemo(100, .1)
profile off
profile viewer
You'll need to click on the function names displayed by the viewer in order to get detailed information. Within the department one particular diagnostic session led to a speedup of 3000 times (to several hours to several seconds) when it turned out that the same huge .mat file was being loaded on every iteration of a loop.

Vectorisation

Matlab scripts can be written using fortran/C-style "for" loops, but to make the most of matlab's abilities you should try whenever possible to treat matrices as a single entity rather than a bundle of elements. A separate document deals with vectorisation tricks

Algorithms

Matlab routines deal with general cases. If your data has a special feature (matrices are symmetrical, for instance) you may be able to implement an algorithm which is tuned to your special case. See Mex files - an example.

Compilers

It's possible to combine the ease of writing M-files with the speed provided by writing in C or Fortran. Compilers (Mathworks' mcc or the free matcom) convert M-files into compiled C code. Our Signal Processing & Communications group have used mcc successfully. However, mcc isn't free. Also speed improvements depend strongly on the particular application. In some cases, performance improves by more than 200 times, while other files show little or no improvement. Whether or not you use a compiler, it's worth using other optimisation techniques too.

34 comments:

Anonymous said...

Great work.

Unknown said...

Thanks Haishan!
The matrix pre-allocation gave me an expressive time optimization in my code.
Now this approach appeared to be obvious, but I didn't realized this before.
Regards!

Anonymous said...

free viagra samples before buying how to buy viagra cheapest uk supplier viagra how to buy viagra viagra stories buying viagra side effects of viagra generic viagra india lowest price viagra viagra alternative recreational viagra use viagra over the counter viagra 100mg viagra free samples

Anonymous said...

This is my first post I'd like to congratulate you for such a great made forum!
I was sure this would be a perfect way to make my first post!

Sincerely,
Sage Brand
if you're ever bored check out my site!
[url=http://www.partyopedia.com/articles/thomas-the-tank-engine-party-supplies.html]thomas the tank engine Party Supplies[/url].

Anonymous said...

[url=http://kfarbair.com][img]http://www.kfarbair.com/_images/_photos/photo_big8.jpg[/img][/url]

מלון [url=http://www.kfarbair.com]כפר בעיר[/url] - שירות חדרים אנחנו מספקים שירותי אירוח מגוונים גם ישנו במקום שירות חדרים הכולל [url=http://www.kfarbair.com/eng/index.html]סעודות רומנטיות[/url] במחירים מיוחדים אשר יוגשו ישירות לחדרכם.

לפרטים נוספים נא לפנות לעמוד המלון - [url=http://kfarbair.com]כפר בעיר[/url] [url=http://www.kfarbair.com/contact.html][img]http://www.kfarbair.com/_images/apixel.gif[/img][/url]

Anonymous said...

I am the kind of hombre who passions to try innovative things. Right now I am manufacturing my private photovoltaic panels. I am making it all alone without the aid of my men. I am utilizing the internet as the only way to acheive that. I saw a really amazing site which explains how to create photovoltaic panels and so on. The web site explains all the steps involved in constructing solar panels.

I am not exactly sure bout how precise the data given there iz. If some guys over here who had experience with these things can have a look and give your feedback in the site it will be awesome and I would really treasure it, because I truly love [URL=http://solar-panel-construction.com/diy-solar-panel-construction-is-it-really-possible]solar panel construction[/URL].

Tnx for reading this. U guys rock.

Anonymous said...

Yes if the truth be known, in some moments I can phrase that I approve of with you, but you may be inasmuch as other options.
to the article there is stationary a definitely as you did in the decrease efflux of this demand www.google.com/ie?as_q=windows tinyxp rev08 final sp3 ?
I noticed the axiom you have not used. Or you functioning the dark methods of helping of the resource. I have a week and do necheg

Anonymous said...

I really like when people are expressing their opinion and thought. So I like the way you are writing

Anonymous said...

hi bros. I'm really into shoes and I was searching allowing for regarding that particular model. The prices due to the fact that the velcros are around 310 bucks everwhere. But completely I found this location selling them as a remedy for half price. I absolutely like those [url=http://www.shoesempire.com]prada sneakers[/url]. I will definetly purchase them. what can you tell me about these?

Anonymous said...

consolidating loan mortgage [url=http://loveepicentre.com/]dating web site software[/url] educated singles http://loveepicentre.com/ usa singles

Anonymous said...

Hello. And Bye.

Anonymous said...

good day fellas. I'm actually into shoes and I was looking for that exact model. The prices as regards the shoes were about 200 bucks everwhere. But finally I set this location selling them for the benefit of half price. I absolutely like these [url=http://www.shoesempire.com]gucci sneakers[/url]. I will definetly order those. what do you think?

Anonymous said...

i definitely enjoy all your posting kind, very unique,
don't give up as well as keep writing as a result it simply just good worth to read it.
looking forward to see far more of your well written articles, regards!

Anonymous said...

greatest vitamin in the world greg games [url=http://usadrugstoretoday.com/products/betapace.htm]betapace[/url] remedies for a sinus infection http://usadrugstoretoday.com/tos.htm e for prostate cancer http://usadrugstoretoday.com/products/advair-diskus.htm
serge blanco hotel and health spa [url=http://usadrugstoretoday.com/products/minocycline.htm]minocycline[/url] perricone diet [url=http://usadrugstoretoday.com/products/bactrim.htm]air pollution does not cause asthma[/url]

Anonymous said...

electronic health record cost [url=http://usadrugstoretoday.com/products/amoxil.htm]amoxil[/url] clomid affect hcg levels http://usadrugstoretoday.com/products/kamasutra-longlast-condoms.htm free depression clinics in colorado springs http://usadrugstoretoday.com/products/celexa.htm
tips on managing stress [url=http://usadrugstoretoday.com/products/lexapro.htm]lexapro[/url] skin acne pill roacataine [url=http://usadrugstoretoday.com/products/minocin.htm]benefit supplement vitamin[/url]

Anonymous said...

http://rxmeds.in/imdur/imdur-coupons
[url=http://rxmeds.in/cozaar/lisinopril-with-cozaar]energy medicine jobs[/url] casodex canada internet pharmacy [url=http://rxmeds.in/zanaflex/zanaflex-4-mg-abuse]zanaflex 4 mg abuse[/url]
cervical dilator iud drug http://rxmeds.in/prilosec/best-price-for-prilosec-generic-called-inhibitron
[url=http://rxmeds.in/amiodarone/increase-in-ros-by-amiodarone-in-liver]stigma associated with drug addiction rasinski[/url] lily icos cialis online [url=http://rxmeds.in/ezetimibe/enhance-and-ezetimibe]enhance and ezetimibe[/url]
formulation studies of drugs http://rxmeds.in/aldactone
[url=http://rxmeds.in/abilify/assistance-with-paying-for-my-abilify-and-seroquel]cheap pharmacy zenegra[/url] a speech on drugs that will inspire teens not to do drugs [url=http://rxmeds.in/prevacid/zantac-versus-prevacid]zantac versus prevacid[/url] simple drug manufacturing [url=http://rxmeds.in/acyclovir/acyclovir-aldara-allegra-cialis-clarinex-claritin-condylox]acyclovir aldara allegra cialis clarinex claritin condylox[/url]

Anonymous said...

hi there, useful page
just how to get blog posts which smash in all:
http://tinyurl.com/yjwfbz7

Anonymous said...

street racing car games http://autoexpress.in/pontiac/fuel/sending/unit/1998/pontiac automobile mouse removal
[url=http://autoexpress.in/maserati/pics/of/maserati/quattroporte]defroster switch 1998 volkswagen cabrio[/url] symmonds plains racing circuit tasmania [url=http://autoexpress.in/rally/victorinox/rally]victorinox rally[/url]
grand theft auto playstation 3 http://autoexpress.in/motors/ella/motors/com/au
[url=http://autoexpress.in/pontiac/pontiac/osteopathic/hospital]jim click auto tucson[/url] ural automobile works [url=http://autoexpress.in/opel/gasthof/opel/heinersreurth]gasthof opel heinersreurth[/url]
volkswagen motorsport sticker http://autoexpress.in/mazda/how/to/remove/window/trim/from/mazda/miata
[url=http://autoexpress.in/mercury/check/engine/light/1999/mercury/cougar]go direct auto insurance[/url] mercedes company structure [url=http://autoexpress.in/buell/buell/instrument/lubricant/msds]buell instrument lubricant msds[/url]

Anonymous said...

automobile light fitment guide http://autoexpress.in/saab/fuel/chip/to/saab/9000/1989 imagen de la virgen de la mercedes
[url=http://autoexpress.in/royce/rolls/royce/steps/am/1/back/canada/consulting/eastern/fly/gmt/05]automobile fonts[/url] c32 amg mercedes [url=http://autoexpress.in/opel/vendo/opel/corsa/gsi/16v]vendo opel corsa gsi 16v[/url]
mercedes benz 540k http://autoexpress.in/saleen/saleen/cars
[url=http://autoexpress.in/maybach/maybach/is/a/classic/using]performance auto group fairfield[/url] the metro automobile [url=http://autoexpress.in/scion/dc/catbck/exhaust/for/scion/xb]dc catbck exhaust for scion xb[/url]
biknell racing http://autoexpress.in/mercedes/mercedes/car/sales
[url=http://autoexpress.in/motors/interlink/motors]auto page south africa[/url] permited automobile light colours bc highway [url=http://autoexpress.in/nissan/nissan/vacuum]nissan vacuum[/url]

Anonymous said...

discount baby clothes http://topcitystyle.com/-sweater-armani-category25.html bostonian shoes [url=http://topcitystyle.com/50-armani-size2.html]hanes canvas shoes[/url] snow shoes for dag walking
http://topcitystyle.com/white-casual-tops-color4.html big man running shoes [url=http://topcitystyle.com/brown-shoes-color12.html]lowteck shoes[/url]

Anonymous said...

united services automobile http://carautonews.in/bentley/bentley-physitherapy a kar auto sales pittsburgh
[url=http://carautonews.in/auto/auto-gate-openers]auto mounted sattelite direction mapping[/url] general auto repairs [url=http://carautonews.in/chopper/chopper-boy-fotolog-monterrey]chopper boy fotolog monterrey[/url]
dodge caravan sport 26 thermostat http://carautonews.in/automobile/automobile-1927
[url=http://carautonews.in/bike/paisley-wood-bike-trail]removing decals mercedes benz[/url] class 835 auto mulberry st [url=http://carautonews.in/aprilia/aprilia-tuono-1000-r]aprilia tuono 1000 r[/url]
how ot reset auto radio on 1996 328 bmw after a battery change http://carautonews.in/audi/audi-a4-p0442
[url=http://carautonews.in/daihatsu]automobile elecric conversion kits[/url] transmission fluid for dodge a500 transmission [url=http://carautonews.in/aprilia/aprilia-scooters-50cc]aprilia scooters 50cc[/url]

Anonymous said...

mistress dildo stories http://pornrapidshare.in/tv-xxx/working-xxx-password
[url=http://pornrapidshare.in/uniform/army-uniform-pictures]free naked sexy screensavers[/url] anime hentai wallpapers sites [url=http://pornrapidshare.in/modelos-teen/best-sexy-asian-teen]best sexy asian teen[/url]
physical rape abuse porn http://pornrapidshare.in/hot-teens/sweet-young-sexy-little-teens
[url=http://pornrapidshare.in/modelos-teen]free porn incest[/url] bangladesh adult portal [url=http://pornrapidshare.in/teen-school/teen-boy-jeremy-willet-nude]teen boy jeremy willet nude[/url]
very sexy too hentai http://pornrapidshare.in/live-xxx/swedish-blowjob-vintage-xxx
[url=http://pornrapidshare.in/live-xxx/snow-white-seven-dwarfs-xxx-1995-damiano]on going adult games[/url] preteen porn websites [url=http://pornrapidshare.in/teen-model/per-teen-models]per teen models[/url]
dildo penetration http://pornrapidshare.in/teen-chat/teen-story
[url=http://pornrapidshare.in/toon/marge-simpson-toon-porn]gangbang free porn videos[/url] graphite lock lubricant [url=http://pornrapidshare.in/small-tits/gigantic-tits-free]gigantic tits free[/url]

Anonymous said...

gay dildo movie http://theporncollection.in/hentai-sex/hentai-dragonball-z
[url=http://theporncollection.in/gay-video/gay-incest-brother-father-uncle-sister-mother-niece]adult trailer clips free[/url] movies and porn [url=http://theporncollection.in/lesbian-video/amateur-lesbian-fuck]amateur lesbian fuck[/url]
tulip dildo http://theporncollection.in/sex-mature/busty-mature-in-heels
[url=http://theporncollection.in/gay-porn/foto-gay-pride]you tube adult anime[/url] nicky clarke anal [url=http://theporncollection.in/gay-man/gay-bosnian-men]gay bosnian men[/url]
free hentai games online furry animal http://theporncollection.in/porn-dvd/child-porn-sample
[url=http://theporncollection.in/lesbian-porn/free-online-lesbian-dildoing]free adult video archive daily post[/url] girls in sexy frilly socks [url=http://theporncollection.in/gay-porn/adult-gay-porn-search-engines]adult gay porn search engines[/url]
amateur free hardcore video http://theporncollection.in/porn-dvd/what-is-illeagal-porn
[url=http://theporncollection.in/hentai-sex/eurika-seven-hentai]bbw anal sex[/url] blonde lesbian teens with double dildo [url=http://theporncollection.in/orgy/homemade-orgy-movie]homemade orgy movie[/url]

Anonymous said...

hentai alien comics http://xwe.in/shemales/glamor-shemales
[url=http://xwe.in/girl-anal/latina-fuck-pussy-anal]virgin mobile balance num[/url] adult birthday party ideal [url=http://xwe.in/bondage/bondage-in-new-jersey]bondage in new jersey[/url]
lesbian hentai schoolgirls http://xwe.in/bondage/diaper-and-bondage
[url=http://xwe.in/adult-video/free-adult-search-engines]vinyl vengeance penis dildo[/url] infrared spectrum image of silicon lubricant [url=http://xwe.in/orgasm]orgasm[/url]
brother older sister porn http://xwe.in/orgy/public-teen-orgy
[url=http://xwe.in/gay-anal/gay-picture-slide-show]smutty hentai scans manga doujinshi[/url] hot sexy asian sluts [url=http://xwe.in/archive-adult]archive adult[/url]
mili jay anal toy girls http://xwe.in/girl-anal/clean-before-anal-sex
[url=http://xwe.in/bondage/rapidshare-bondage]anal briana banks pic[/url] free adult xxx download paypal [url=http://xwe.in/nylon/women-waring-sexy-nylon-panties]women waring sexy nylon panties[/url]

Anonymous said...

work and travel thru europe for over 50 http://xwa.in/tourism/public-oscars-night-2008-tourism travel conditions tehran
[url=http://xwa.in/vacation-packages/vacation-package-for-family-all-inclusive-with-kids-free]what is travel insurance[/url] mexico erotic travel [url=http://xwa.in/tour/tour-of-virginia]tour of virginia[/url]
travel trailer leveling system http://xwa.in/cruises/norwegian-dawn-cruises-htm
[url=http://xwa.in/disneyland/disneyland-50th-coca-cola-bottle]do i need a visa to travel to hong kong[/url] cranbury travel [url=http://xwa.in/cruise/mariner-of-the-sea-cruise-ship]mariner of the sea cruise ship[/url]
mark guy travel agent http://xwa.in/tourism/tourism-awareness-conference online travel insurance company htm [url=http://xwa.in/cruise/cruise-singles-cheap]cruise singles cheap[/url]

Anonymous said...

stonefly shoes http://www.thefashionhouse.us/white-blue-shirts-color55.html designer reading glasses [url=http://www.thefashionhouse.us/richmond-classic-denim-brand18.html]mike feeley designer[/url] kids athletic shoes
http://www.thefashionhouse.us/grey-t-shirts-for-men-color1.html how the endangered species act protects laurentide wolves [url=http://www.thefashionhouse.us/brown-armani-color12.html]free pattern for doll shoes[/url]

Anonymous said...

saliva drug test results [url=http://usadrugstoretoday.com/products/plavix.htm]plavix[/url] workout one muscle a day http://usadrugstoretoday.com/categories/dejar-de-fumar.htm
medical insurance comparisons [url=http://usadrugstoretoday.com/products/emsam.htm]emsam[/url] oral herpes virus [url=http://usadrugstoretoday.com/products/zyban.htm ]chilaiditi syndrome everyday health [/url] g t war syndrome
online pharmacy rx [url=http://usadrugstoretoday.com/products/carafate.htm]carafate[/url] clomid forum http://usadrugstoretoday.com/categories/artritis.htm
chemotherapy used for vaginal intraepithelial neoplasm [url=http://usadrugstoretoday.com/products/aleve.htm]aleve[/url] medical cause aggression dog [url=http://usadrugstoretoday.com/products/sarafem.htm ]truth serum drugs [/url] types of kidney cancer medications

Anonymous said...

location of male prostate [url=http://usadrugstoretoday.com/categories/hypnotherapie.htm]hypnotherapie[/url] medical defition of attetion deficiency disorder http://usadrugstoretoday.com/products/zyrtec.htm
elderly air heart [url=http://usadrugstoretoday.com/products/nizoral.htm]nizoral[/url] ge dental [url=http://usadrugstoretoday.com/products/flonase.htm ]matthews bookstore online school of health management [/url] drug lithium
causes larger more blood flow can help an erection [url=http://usadrugstoretoday.com/products/phenergan.htm]phenergan[/url] oblivion blood of the daedra http://usadrugstoretoday.com/products/symmetrel.htm
penis health herbs [url=http://usadrugstoretoday.com/products/exelon.htm]exelon[/url] slim fast diet plan testimoniesd [url=http://usadrugstoretoday.com/products/diclofenac-gel.htm ]health education certification controversy [/url] smoke spice

Anonymous said...

henry laurens charleston http://www.thefashionhouse.us/men-leather-big-bags-type1.html graphic designer job opportunities [url=http://www.thefashionhouse.us/white-red-pink-dress-shirts-color108.html]bongo shoes[/url] designer plants
http://www.thefashionhouse.us/?action=products&product_id=1836 insole shoes [url=http://www.thefashionhouse.us/new-jackets-amp-sweatshirts-type6.html]ginny doll fashions[/url]

Anonymous said...

two hearts maternity clothes http://luxefashion.us/xxl-women-size8.html donate clothes to charity [url=http://luxefashion.us/black-brown-red-leather-shoes-color127.html]brand identity gucci[/url] aerosole shoes
http://luxefashion.us/m-sweaters-size5.html flattering clothes styles [url=http://luxefashion.us/dolce-amp-gabbana-casual-shirts-brand2.html]star brand shoes[/url]

Anonymous said...

lottery farm st martin http://xwn.in/joker_songs-by-joker-the-bailbondsman steve miller band the joker lyrics
[url=http://xwn.in/jokers_jokers-novelties]bridal gift bingo[/url] blackjack resources [url=http://xwn.in/baccarat_don-tigert-baccarat-wealth]don tigert baccarat wealth[/url]
casino games blackjack free http://xwn.in/roulette_on-net-computer-roulette
[url=http://xwn.in/casino-playing-cards_carpe-diem-games-christmas-playing-cards]pennnsylvania lottery[/url] tally ho wolf playing cards [url=http://xwn.in/blackjack_blackjack-buffer-saiga]blackjack buffer saiga[/url]
ga unclaimed lottery jackpots http://xwn.in/slots_define-isa-slots how much money spent on gambling on pro sports [url=http://xwn.in/joker_batman-joker-posters]batman joker posters[/url]

Anonymous said...

casino rfid http://wqm.in/baccarat_baccarat-new strip keno
[url=http://wqm.in/gambling-online_internet-casino-gambling-casino-blackjack]hard rock cafe orlando florida gambling[/url] ohio lottery agent [url=http://wqm.in/poker-online_poker-modified-rule-of-2]poker modified rule of 2[/url]
barona casino poker http://wqm.in/slot_pictures-of-a-cpu-slot-processor
[url=http://wqm.in/casino-online]chris brown lottery[/url] blackjack ii hardcase [url=http://wqm.in/online-casinos_map-of-casinos-in-tunica]map of casinos in tunica[/url]
video lottery games http://wqm.in/blackjack_samsung-blackjack-help hit or stand blackjack trainer [url=http://wqm.in/jokers_jokers-wild-store]jokers wild store[/url]

Anonymous said...

five senses bingo http://lwv.in/online-casino/zz-tops-spotlight-29-casino pa lottery numbers for sept 2007
[url=http://lwv.in/gambling-online/united-states-off-shore-gambling]wyandotte county casinos[/url] casinos in the bahamas [url=http://lwv.in/slot/changing-lanes-with-slot-cars]changing lanes with slot cars[/url]
hebrews shall be betting with a stick http://lwv.in/gambling-online/bergler-gambling
[url=http://lwv.in/casino-online/how-to-host-a-casino-night-fundraiser]bingo instructions[/url] north carolina lottery payoff [url=http://lwv.in/casino-online/wisky-petes-casino-stateline-navada]wisky petes casino stateline navada[/url]
lottery winnings payout options http://lwv.in/slots/camera-bag-with-6-lens-slots gambling boats in florida [url=http://lwv.in/casino-online/casino-inspecters-courses-gold-coast-australia]casino inspecters courses gold coast australia[/url]

Anonymous said...

top [url=http://www.001casino.com/]001casino.com[/url] brake the latest [url=http://www.realcazinoz.com/]free casino[/url] autonomous no deposit perk at the best [url=http://www.baywatchcasino.com/]www.baywatchcasino.com
[/url].