Loren on the Art of MATLAB

March 25th, 2009

Four Color Images

I recently attended a show at the Institute for Contemporary Art in Boston featuring work by Shepard Fairey. It got me thinking how simple it can be in MATLAB to make a 4-color image and adjust it however you like.

Contents

Import Image

First, let me get an image. This one is a gray-scale image.

Ic = imread('pout.tif');
imshow(Ic)

Note: I am using imshow from Image Processing Toolbox to help manage the color and axes scaling.

Define Four Colors

Next let me choose a palette of colors, and display them.

lilac = [.5 .4 .9];
darkblue = [.1 .3 .8];
lightblue = [0 .5 .6];
red = [.8 0 0];
cm = [darkblue;  red; lightblue;  lilac];
image([1 3;2 4]),colormap(cm), axis off

Segment Gray Image into Four Levels

Next I choose levels for grouping pixel values into 4 color bins. The minimum and maximum values of my image are close enough to 0 and 255 to not bother stretching the range.

min(Ic(:))
max(Ic(:))
ans =
   74
ans =
  224

My first attempt at binning creates equal size bins.

levels = linspace(0,255,5)
levels =
            0        63.75        127.5       191.25          255

Next I create a new image by combining 4 binary images with the appropriate multipliers.

Idb = (Ic <= levels(2));
Ir = Ic<=levels(3) & Ic>levels(2);
Ilb = Ic<=levels(4) & Ic>levels(3);
Ipy = Ic<=levels(5) & Ic>levels(4);
Ic4 = Idb+2*Ir+3*Ilb+4*Ipy;
imshow(Ic4,cm)

Change the Order of Colors

What happens when I change the color order? Features appear different with different color selections.

cm = [darkblue;  lightblue;  lilac; red];
imshow(Ic4,cm)

Change Ranges for Four Colors to Bring Out Details

Now I finetune the color bins to emphasis more detail from the original image. I then recalculate the binary images according to the new bins and recombine them.

levels = [0 90 128 155 255]
Idb = (Ic <= levels(2));
Ir = Ic<=levels(3) & Ic>levels(2);
Ilb = Ic<=levels(4) & Ic>levels(3);
Ipy = Ic<=levels(5) & Ic>levels(4);
Ic4 = Idb+2*Ir+3*Ilb+4*Ipy;
imshow(Ic4,cm)
levels =
     0    90   128   155   255

Colormaps are Important

Choosing appropriate colormaps for displaying data is very important. You need to be careful to not exaggerate unimportant details. Here's an interesting reference from one of my geophysics periodicals.

A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004.

Do you have any special colormaps you use for exploring or displaying your data? If so, can you post information (perhaps with links of plots to look at) here?


Get the MATLAB code

Published with MATLAB® 7.8

March 13th, 2009

Using str2func for Anonymous Function Handle Creation

Starting in Release 2009a, str2func lets you create a handle to anonymous function. Before that, you need to construct an anonymous function from literal strings, or using some ugly code involving eval.

Contents

The Past

Since the introduction of anonymous functions in MATLAB version 7, you could create an anonymous function like this:

multiplier = 17;
myfactor = @(x) multiplier*x;

The applying the function does what you expect.

x = rand(1,4)
y = myfactor(x)
x =
      0.42176      0.91574      0.79221      0.95949
y =
       7.1699       15.568       13.468       16.311

I have just created a function that, when applied, multiplies its input by the value defined by multiplier (its value when myfactor was created).

multiplier = 42
y = myfactor(x)
multiplier =
    42
y =
       7.1699       15.568       13.468       16.311

Creating an Anonymous Function Inside a Function

Suppose I want to create an anonymous function, inside another function. And the information for the function to create is passed into the function. You can run into a problem if the function inside which you are creating the anonymous function happens to have some name, perhaps a subfunction, that is the same as the user input name. Using a solution involving eval would pick up the reference to the subfunction instead of the intended function outside the scope of the file. Here's an example.

   function anon = myfun(X,fun)
   anon = str2func(['@(',X,')',fun,'(',X,')']);
   function meshgrid
   disp(17)

What happens if you try to call myfun with fun = 'meshgrid'

 anon = myfun('x,y','meshgrid');

If you now use anon, e.g., [a,b] = anon(x,y), you will get the version of meshgrid on your path, not the one local to myfun. If instead you change str2func in myfun to eval, then anon(x,y) will use the subfunction meshgrid, which you most likely didn't intend, and certainly a user of your code would be surprised.

Does This Help?

Does this extended functionality in str2func help you with any of your applications? Let me know here.


Get the MATLAB code

Published with MATLAB® 7.8

March 3rd, 2009

What’s in Your startup.m?

Several of us at The MathWorks were recently discussing how we each use startup.m.

Contents

What is startup.m?

I typically don't use startup.m, but when I do, I have one sitting in a particular directory where there's other code I want to use as well. And I make a MATLAB shortcut in that directory (this is using Windows) that specifies this particular directory as the starting location for MATLAB. When you use this icon for starting MATLAB, it starts in the specified directory, and finds and runs the startup.m located there. I usually do this for presentations that I give, so my startup.m generally includes commands that change default font sizes for figures so the annotations are visible in a large, dimly lit room. I have also helped users customize their own startup.m. Commonly, the contents again includes commands to set up preferences for graphics, for example, to have grid on by default (use something like this: set(0,'defaultAxesXGrid','on'), and similarly for 'YGrid' and 'ZGrid'). I've also seen users randomize the starting point for creating random numbers.

finish.m Anyone?

The analog to startup.m is finish.m. This can be used to save data, ask for confirmation to quit, release a hardware resource, finish writing out a file, etc.

What Do You Use startup.m For?

Do you use startup.m or finish.m? If so, I'd love to hear what you put in these. Post your thoughts here.


Get the MATLAB code

Published with MATLAB® 7.7

February 24th, 2009

Decomposing Embedded Images

Today I’d like to introduce a guest blogger, Jiro, who is an application engineer here at The MathWorks. Some of you may know him as one of the bloggers for the File Exchange Pick of the Week.

Contents

I recently presented to a group of freshman engineering students at Virginia Commonwealth University. I wanted to show something that was fun, eye-catching, and relatively easy to explain. So I created this image-related demo. I am not an expert in image processing, but I certainly had a lot of fun working on this example. For anyone interested in hardcore image processing, I would suggest also taking a look at Steve's Image Processing blog.

This example demonstrates how to embed an image into another image and how to decompose the images. The embedded image is created by storing two 8-bit RGB image as 16-bit RGB image. The primary image is stored in the most significant byte, while the secondary image is stored in the least significant byte. (See the section titled "Embed Function & Decode Function" of this post for the code). With this method, the secondary image can be concealed inside the primary image, without any loss of information.

This post focuses on the decomposition part of the demo.

This demo uses functions from the Image Processing Toolbox.

Setup

curImshowBorder = iptgetpref('ImshowBorder');
iptsetpref('ImshowBorder', 'tight');

Show Images

Here are two images that look the same. But are they??

  • peppers_BlueHills.png

  • peppers_trees.png

Would you believe me if I say these were very different images? Perhaps you'll believe MATLAB:

isequal(imread('peppers_BlueHills.png'), imread('peppers_trees.png'))
ans =
     0

In fact, they have completely different images embedded in them. You just can't tell with the naked eye.

Image Decomposition

Let's try to decompose the image and see what's hidden inside.

These are 16-bit RGB images. See the "Embed Function & Decode Function" section of this report to see the function that I used for creating these images.

imData = imread('peppers_BlueHills.png');
whos imData
  Name          Size                 Bytes  Class     Attributes

  imData      384x512x3            1179648  uint16              

The image contains two 8-bit images. The primary image is stored in the most significant byte and the secondary image is stored in the least significant byte.

Convert RGB 3-D Array to a Vector

We'll be using TYPECAST to convert the data type, and the function requires a vector.

pixelVals = imData(:);
pixelVals(1:10)
ans =
  16097
  16352
  16862
  16348
  16346
  16344
  16087
  16854
  16082
  15822

Convert UINT16 to UINT8

Next, convert the data type from UINT16 to UINT8. In doing so, we'll use TYPECAST (instead of CAST) to preserve the data.

pixelValsConv = typecast(pixelVals, 'uint8');
whos pixelVals*
  Name                     Size              Bytes  Class     Attributes

  pixelVals           589824x1             1179648  uint16              
  pixelValsConv      1179648x1             1179648  uint8               

Notice that pixelValsConv has twice as many elements. This is because there are two 8-bit values to a 16-bit value.

Separate Two Images

We'll reshape them to separate out the least and the most significant bytes.

pixelValsConv = reshape(pixelValsConv, 2, [])';
pixelValsConv(1:10, :)
ans =
  225   62
  224   63
  222   65
  220   63
  218   63
  216   63
  215   62
  214   65
  210   62
  206   61

On a system with "little-endian" architecture, the first column is the least significant byte and the second column is the most significant column.

 (first pixel)  62*256 + 225 = 16097

On a "big-endian" architecture system, the order is switched.

[cmp,maxsize,endian] = computer

if strcmp(endian, 'L')
  imOrder = [2 1];
else
  imOrder = [1 2];
end
cmp =
PCWIN
maxsize =
  2.1475e+009
endian =
L

We'll take each column and reshape them as the primary and secondary images.

imDataPrimary   = reshape(pixelValsConv(:, imOrder(1)), size(imData));
imDataSecondary = reshape(pixelValsConv(:, imOrder(2)), size(imData));

We can see that we end up with two images, both of which are now UINT8 images.

whos imData*
  Name                    Size                 Bytes  Class     Attributes

  imData                384x512x3            1179648  uint16              
  imData2Primary        384x512x3             589824  uint8               
  imData2Secondary      384x512x3             589824  uint8               
  imDataPrimary         384x512x3             589824  uint8               
  imDataSecondary       384x512x3             589824  uint8               

Show Primary and Secondary Images

figure;imshow(imDataPrimary);
figure;imshow(imDataSecondary);

Decomposing the Second Image

We'll do the same thing for the second image we read in. Let's see what's embedded in that one. We'll use decodeImage.m which is a function with the above algorithm.

[imData2Primary, imData2Secondary] = decodeImage('peppers_trees.png');
figure; imshow(imData2Primary);
figure; imshow(imData2Secondary);

How It Works

So, how does this work? Why is the secondary image unrecognizable by the naked eye? That's because the secondary image is stored in the least significant byte.

To understand this, let's take a look at a single row of pixels in one of the RGB planes. We'll look at row 150 of the red plane.

pixelRow16 = imData(150, :, 1);  % row 150, red plane

We covert this vector to UINT8 using TYPECAST:

pixelRow8 = typecast(pixelRow16, 'uint8');
pixelRow8 = reshape(pixelRow8, 2, []);
pixelRow8(:, 1:10)
ans =
   64   60   61   61   57   60   61   61   61   61
   67   70   71   70   70   72   74   69   63   63

On a little-endian architecture system, the first row is the secondary image, and the second row is the primary image. Next, we'll create a UINT16 vector with only the primary image.

% set the secondary image vector to ZERO
pixelRow8Main  = [zeros(1, size(pixelRow8, 2), 'uint8'); pixelRow8(2, :)];
pixelRow16Main = typecast(pixelRow8Main(:)', 'uint16');

Now, let's compare the values of the total image vector with those of the primary image vector.

figure;
ax1 = axes;hold on;
plot(pixelRow16);
plot(pixelRow16Main, 'r');
xlabel('Pixel Count'); ylabel('Pixel Value (UINT16)');
legend('Total Image', 'Primary Image', 'Location', 'NorthWest');
rectX = 160; rectY = 15000; rectW = 30; rectH = 3500;
rectangle('Position', [rectX, rectY, rectW, rectH]);
dar = get(ax1, 'DataAspectRatio'); dar = dar(2)/dar(1);
w = .3; h = w*(rectH/rectW)/dar;
ax2 = axes(...
  'Units', 'Normalized', ...
  'Position', [.6 .2 w h], ...
  'Box', 'on', ...
  'LineWidth', 2, ...
  'XTick', [], ...
  'Ytick', [], ...
  'Color', [.95 .95 .95]);hold on;
xlabel('Magnified Region');
plot(pixelRow16);
plot(pixelRow16Main, 'r');
xlim([rectX, rectX+rectW]);
ylim([rectY, rectY+rectH]);

As this figure shows, the primary image represents the majority of the information. The information for the secondary image is much smaller relative to the primary image. But if we look at the data for the secondary image by itself, you see that we have the full 8-bit information.

figure;
plot(pixelRow8(1, :), 'g'); ylim([0 300]);
legend('Secondary Image', 'Location', 'NorthWest');
title('Secondary Image');
xlabel('Pixel Count'); ylabel('Pixel Value (UINT8)');

The following animations show how the secondary image data becomes more apparent as we subtract out the primary image data. Animations created using ANYMATE.

  • 2-D Animation

  • 3-D Animation

Embed Function & Decode Function

These are the actual functions for creating and decoding embedded images.

help embedImage
  EMBEDIMAGE  Embed an image into another image
    EMBEDIMAGE(PRIMARYIMAGE, IMAGETOEMBED) embeds the image file
    IMAGETOEMBED into the image file PRIMARYIMAGE. Both PRIMARYIMAGE and
    IMAGETOEMBED must be valid file names.
 
    The image files must be 8-bit images. The output image file will be a
    16-bit PNG image, named PRIMARYIMAGE_IMAGETOEMBED.png. The primary
    image data will be stored in the most significant byte and the
    embedded image data will be stored in the least significant byte.
 
    Example:
      embedImage('trees.tif', 'football.jpg');
 
    See also DECODEIMAGE.
 
  Jiro Doke
  Jan 24, 2009.

help decodeImage
  DECODEIMAGE  Decode embedded image.
    DECODEIMAGE(IMAGEFILE) decodes embedded image file IMAGEFILE.
    IMAGEFILE must be a valid file name. It will display a figure with 3
    axes. The top axis is the original image. The bottom left is the
    primary image, and the bottom right is the embedded hidden image.
 
    [PRIMARY, HIDDEN] = DECODEIMAGE(IMAGEFILE) returns the primary image
    and the hidden image data as RGB data.
 
    This function only works on images created by embedImage.m.
 
    Example:
      % create embedded image
      embedImage('trees.tif', 'football.jpg');
      decodeImage('trees_football.png');
 
    See also EMBEDIMAGE.
 
  Jiro Doke
  Jan 24, 2009.

Cleanup

iptsetpref('ImshowBorder', curImshowBorder);

Comments?

I hope you liked this example. Images make nice examples because they are visual. Let me know if you have other fun, pedagogical examples that involve graphics. Put them on the File Exchange, and I'll be sure to take a look at it as a potential Pick of the Week!


Get the MATLAB code

Published with MATLAB® 7.7

February 17th, 2009

Experiments with MATLAB - The Book

Quite a few MATLAB users that I meet these days want to know if The MathWorks has a toolbox for their precocious teenagers. Currently, there is not such product. However, Cleve Moler, cofounder of The MathWorks, has a book, Experiments with MATLAB that you might find suitable.

Cleve is an engaging writer; his love for math and teaching shine through. Cleve has written other books as well. Prior to Experiments with MATLAB, Cleve most recently wrote Numerical Computing with MATLAB.

Cleve's audience for each of these books is quite different; the former intended for high school and early college, the latter for an introduction to numerical methods. You may notice that the these two books share some chapters with the same titles, e.g., "Linear Equations." Despite the naming similarities, Cleve focuses appropriately in each book on the intended audience.

In Experiments you will see a 7-page chapter using a high school level word problem to motivate the discussion. In contrast, Cleve spends about 40 pages on the equivalent chapter in the Numerical Computing book for the equivalent chapter.

Here's a list of the chapters.

Tell us your experiences of teaching your high school kids to use MATLAB. What sorts of problems did they work on? What was easy? What was hard? Let us know here.

Update: High school students can purchase and use the Student Version, which is available for a pretty good price and delivered by download at the MathWorks store ($99).


Get the MATLAB code

Published with MATLAB® 7.7

February 11th, 2009

More MathWorks Bling for Grabs

Recently I posted about some "hidden" MathWorks swag in the LA area. Congratulations to Tony who posted some information on his find. He photographed the location as well as some video.

Today you might find another led/laser flashlight in the Miami area. A hint for you: Back corner, down low, hidden like a pearl. A location with a great view. Take a moment to "soak it in."

Please post here if you are the one to find the flashlight. Please include links to pictures or videos if you take any! Good luck and have fun.


Get the MATLAB code

Published with MATLAB® 7.7

February 2nd, 2009

A Pedagogical Tool for Fourier Transforms

I recently attended the DSP Workshop sponsored by the IEEE Signal Processing Society. It focues on both signal processing and signal processing education. I spoke to a lot of the attendees. Some of the professors and instructors mentioned how important it is to teach the basics solidly first, before going into more depth. If the students don't get the fundamentals, then going further doesn't help.

Contents

Pedagogical Tool - dftmtx

With that context, I asked how they teach Fourier transforms, especially once they go from the analog domain to the digital. It turns out that most of them were unaware of some of the tools in Signal Processing Toolbox, such as dftmtx.

Here's the help.

h = help('dftmtx');
disp(h(1:744))
 DFTMTX Discrete Fourier transform matrix.
    DFTMTX(N) is the N-by-N complex matrix of values around
    the unit-circle whose inner product with a column vector
    of length N yields the discrete Fourier transform of the
    vector.  If X is a column vector of length N, then
    DFTMTX(N)*X yields the same result as FFT(X); however, 
    FFT(X) is more efficient.
 
    The inverse discrete Fourier transform matrix is
    CONJ(DFTMTX(N))/N.
 
    An interesting example is 
 
      D = dftmtx(4)
 
    which returns
 
      D = [1   1   1   1
           1  -i  -1   i     
           1  -1   1  -1
           1   i  -1  -i]
 
    which illustrates why no multiplications are necessary for
    4-point DFTs.
 
    See also FFT and IFFT.


The help also mentions fft, the discrete Fourier transform, computed with a fast Fourier transform (fft) algorithm. With the information given for dftmtx, let's compare results with those of fft.

More on dftmtx

On further inspection, you may notice that there are comments in the file outlining the calculation. As an aside, the computation is actually done using the function fft in MATLAB.

Here's a brief description of the non-|fft| algorithm. Basically calculate frequencies on the unit circle and multiply by sqrt(-1) (w). Multiply these by integral steps for the number of points in the transform (w*x). And then calculate all the sin and cos terms using exp.

Explicitly, the calculation is:

 f = 2*pi/n;                 % Angular increment.
 w = (0:f:2*pi-f/2).' * i;   % Column.
 x = 0:n-1;                  % Row.
 D = exp(-w*x);              % Exponentiation of outer product.

Compare fft and Discrete Transform Matrix Methods

n = 1024;
X = eye(n);
Xf = fft(X);       % fft result
f = 2*pi/n;
w = (0:f:2*pi-f/2).' * 1i;
x = 0:n-1;
Xd = exp(-w*x);     % matrix representation
norm(Xf-Xd)
ans =
  1.6769e-011

Do You Have Good Links for Fourier Transform Teaching Material?

If you know of web sites with good material for teaching discrete Fourier transforms, would you please post them here? Thanks.


Get the MATLAB code

Published with MATLAB® 7.7

January 26th, 2009

Opportunity to Hunt for MathWorks Swag

Have you ever gotten involved in geocaching? Have you ever wanted a MathWorks laser pointer / flashlight? You have a chance of combining both of these interests if you happen to be near the Los Angeles (used to incorrectly say Bay) area in California.

Sam Mirsky has posted the challenge to the MATLAB newsgroup.

Here's a couple of pictures of the swag from my phone camera.

I1 = imread('laser1.jpg');
I2 = imread('laser2.jpg');
whos
  Name        Size                  Bytes  Class    Attributes

  I1        960x1280x3            3686400  uint8              
  I2        960x1280x3            3686400  uint8              
  J1        240x320x3              230400  uint8              
  J2        240x320x3              230400  uint8              

Let me downsample the pictures to display in the blog using imresize from Image Processing Toolbox. You can a learn more about image processing on Steve's blog.

J1 = imresize(I1,.25);
imshow(J1)
J2 = imresize(I2,.25);
imshow(J2)

Don't forget the hint: Underground, but not buried, in a round hole. If you find it, in addition to returning the code to Sam, can you please post here? Have fun!


Get the MATLAB code

Published with MATLAB® 7.7

January 20th, 2009

More Ways to Find Matching Data

Today on the newsgroup, a user wanted help finding when values in a matrix matched some other values (see the post). There was already a solution posted when I was reading, but something about this problem kept nagging at me. So I've invested a little bit of time thinking more about the problem.

Contents

Sample Data

Here's sample data, and the user wants to find all the places in A which have values that match values in B. Simple enough statement.

A = [11 22 34 56 89
23 44 11 20 66
79 54 32 17 89
11 66 21 45 90]
B = [11 66 44 40 90]
A =
    11    22    34    56    89
    23    44    11    20    66
    79    54    32    17    89
    11    66    21    45    90
B =
    11    66    44    40    90

Bruno's Solution - Column-wise Solution

As I said, there was already a solution when I was reading. Here it is.

RESULTS = zeros(size(A));
for i = 1: size(B,2)
    RESULTS = RESULTS + ( A == B(1,i) );
end
RESULTS
RESULTS =
     1     0     0     0     0
     0     1     1     0     1
     0     0     0     0     0
     1     1     0     0     1

The idea here is to create the right size output, and cycle through the values in B (the smaller array for the user's example). Check to see where a given value in B matches one in A, and add a 1 to the RESULTS when those hits are found.

Find Exact Location Matches

To be honest, I misread the question at first, and came up with the following code. However, it does not solve the problem as stated!

C = ~(A-repmat(B,size(A,1),1))
C =
     1     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     1     1     0     0     1

The reason I tried the solution with repmat was so I could first get the right answer, and then find a solution instead with bsxfun. Instead, this solution (which could be quite costly due to the repmat) looks to match values in specific column locations. In other words, the wrong problem solved.

Find Presence - Row-wise Solution

Wising up a very tiny amount, that I was solving the wrong problem, I next tried finding matches by row in A.

Z = zeros(size(A));
for k = 1:size(A,1)
    Z(k,:) = ismember(A(k,:),B);
end
Z
Z =
     1     0     0     0     0
     0     1     1     0     1
     0     0     0     0     0
     1     1     0     0     1

At least this time I get the right answer and am solving the right problem! But this normally would take longer than Bruno's approach because the user premise was that A was huge and B wasn't nearly so large.

isequal(Z,RESULTS)
ans =
     1

The reason I tried this approach was to then see if could convert it to something using arrayfun, or perhaps cellfun.

Another Solution

Finally I had some coffee however! And thank goodness. The answer was in front of me all along. And I was already using it before: ismember.

FinalAnswer = ismember(A,B)
FinalAnswer =
     1     0     0     0     0
     0     1     1     0     1
     0     0     0     0     0
     1     1     0     0     1
isequal(FinalAnswer, RESULTS)
ans =
     1

In one fell swoop I can compute the entire result because I don't care about matching those locations. It's enough to say that a value in A matches some value in B. Voila!

Other Approaches

I just showed you a few approaches for solving this problem. Do you have similar problems, perhaps ones that don't yield as simple a solution? Or do you have other approaches to solving this problem that might be useful, especially in more complicated situations? Please share them here.


Get the MATLAB code

Published with MATLAB® 7.7

January 6th, 2009

Nested Timing

Did you know that you can use tic and toc to measure times of operations that may have other timed operations nested inside?

Contents

Example

Suppose I want to see how long some operations take, and the overall calculation as well. Let's see how long it takes to create some magic squares and how long it takes to find the rank for each one.

Nsizes = [10 20 50 100 200 500 1000];
N = numel(Nsizes);
magTimes = zeros(1,N);
rankTimes = zeros(1,N);
ranks = zeros(1,N);
timeTemp = tic;
for k = 1:N
    mTemp = tic;
    m = magic(Nsizes(k));
    magTimes(k) = toc(mTemp);
    rTemp = tic;
    ranks(k) = rank(m);
    rankTimes(k) = toc(rTemp);
end
allTimes = toc(timeTemp);

Compare Times

If I sum the times for creating the magic squares and computing their ranks, I should get the same time as the overall time calculation, right?

totTimes = sum(magTimes)+sum(rankTimes)
totTimes =
        4.0211
allTimes
allTimes =
       4.0344

The totals don't match! That's because there's other stuff going on in the loop, including overhead for managing the loop.

Timing Tips

To get relative time estimates, you can use the profiler, tic/toc, or Steve's timeit function on the file exchange. Though I am not doing so in this post, you generally should time functionality written in functions, especially if getting the best performance is your goal.

What are Your Timing Patterns?

Do you find yourself timing nested calculations? Do you have other strategies? Please post them here.


Get the MATLAB code

Published with MATLAB® 7.7


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

These postings are the author's and don't necessarily represent the opinions of The MathWorks.