Loren on the Art of MATLAB

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

December 22nd, 2008

I-COOL - International Coalition of Ocean Observing Laboratories

It's no secret that my background is in marine geophysics. Last week at the annual meeting of AGU (American Geophysical Union), I remembered seeing some very cool plots recently, some from MATLAB. I tracked them back to I-COOL where there are a bunch of projects, such as the Atlantic Crossing, many involving undergraduates for their first forays into research, and the excitement they encounter.

Are you working on a research project either as an undergrad or with one, using MATLAB? Please post your story and website here.


Get the MATLAB code

Published with MATLAB® 7.7

December 11th, 2008

When MATLAB Refreshes Directories

Over the years, there have been lots of questions about when MATLAB recognizes files on the path. Today I'm going to talk about the case where a user generates or updates MATLAB code, and then wants to use it. What do you have to do to be sure MATLAB sees it? I am specifically talking about user files in user directories and NOT about files underneath matlabroot.

Contents

function fcnPuzzle()

Note: I am doing an experiment by publishing a function with subfunctions so you can see the code with the benefit of syntax highlighting for the code that's not the blog-code itself. I hope this ends up working and being helpful.

The Code That Perplexed

See the function fcnBug towards the bottom of this post. One puzzle is that if you run the code from the debugger, the results are always the expected ones, but not when running the usual way. I'll illustrate the conundrum by running it a few different ways. Also see the repaired version fcnBugRepair following the buggy version.

Show the file doesn't exist.

exist('fcnTest.m','file')
ans =
     0

Small puzzle. If I don't put my first attempt, before the file exists, into a try-catch, my function fails with an error. However, if I place the same code inside a try-catch, it seems to not generate the error. Let's ignore that mystery for today.

try
    fcnBug( 'C', 'clear')
catch ignoreException
    disp('error when file doesn''t exist before running')
end

Only the original function written out is called, not the updated versions, assuming we do nothing else in the function to affect the workspace.

  for d=1:4
     fcnBug( num2str(d), 'nothing')
  end
1 Problem
1 Problem
1 Problem
1 Problem

Clearing the function before calling it helps.

  for d=1:4
     fcnBug( num2str(d), 'clear')
  end
1 Problem
2 Problem
3 Problem
4 Problem

Another way to influence MATLAB to see the new function is to ask if the file exists.

  delete fcnTest.m
  for d=1:4
     fcnBug(num2str(d), 'clear+exist')
  end
1 Problem
2 Problem
3 Problem
4 Problem

Clean up.

delete fcnTest.m

Fixing the Problem

There is an easy solution to being sure that the new file is recognized. Directly after closing the file, force MATLAB to clear the one in memory. You can do this with a lighter or heavier hand, depending on your situation. Simply clearing the function is enough, or you might try to rehash the files MATLAB knows about.

try
    fcnBugRepair( 'C', 'clear')
catch ignoreException
    disp('error when file doesn''t exist before running')
end
error when file doesn't exist before running

Let me show this working with the repaired function. This was the case earlier in which only the file originally written out was called. You can see here that each version is now executed, even when nothing additional is done (except the addition of the clear statement in the function code).

for d=1:4
   fcnBugRepair( num2str(d), 'nothing')
end
1 Problem
2 Problem
3 Problem
4 Problem

As before, clearing the workspace before execution still has the good effect.

for d=1:4
   fcnBugRepair( num2str(d), 'clear')
end
1 Problem
2 Problem
3 Problem
4 Problem

Again, the test for function existence also works.

delete( 'fcnTest.m');
for d=1:4
    fcnBugRepair(num2str(d), 'clear+exist')
end
1 Problem
2 Problem
3 Problem
4 Problem

Clean Up

delete fcnTest.m

Why Does This Solution Work?

The problem is that of timestamp resolution for the file, which on most filesystems is only 1 second. Since this is being run in a tight loop, the file fcnTest.m is being rewritten during the same clock tick and therefore MATLAB has no way of knowing that it has changed. Therefore, MATLAB originally continued to use the cached version.

clear forces MATLAB to dump its cache, and the next time MATLAB runs the function it reloads it from disk.

The functions exist and rehash each cause MATLAB to notice the file change because they each refresh "dirty" directories.

The reason MATLAB doesn't always look for changes is for performance. fclose does notify the path manager that a certain directory is changed but the cache update won't happen until someone explicitly refreshes the directory -- the refreshing can happen in the ways I've already discussed, or at the next command prompt (that is why it works in debugger).

Original Function

function fcnBug( id, mode)
% fcnBug - unexpected bug
%
% %% Error
% % when the file does not exist before run
% fcnBug( 'C', 'clear')
% %% Only the 'base workspace one'
% % is called
% for d=1:4
%    fcnBug( num2str(d), 'nothing')
% end
% %% Clear the workspace
% % helps
% for d=1:4
%    fcnBug( num2str(d), 'clear')
% end
% %% Not at creation time
% delete( 'fcnTest.m');
% fcnBug( num2str(1), 'clear')
% %% Exists
% % seems to tell to MATLAB that a function is here
% delete( 'fcnTest.m');
% for d=1:4
%    fcnBug(num2str(d), 'clear+exist')
% end
fid = fopen('.\fcnTest.m', 'w');
fprintf(fid, 'function fcnTest(varargin)\ndisp(''%s Problem'')', id);
fclose(fid);

switch lower(mode)
    case 'clear+exist'
        clear fcnTest
        exist( 'fcnTest.m', 'file');
    case 'clear'
        clear fcnTest
    case 'nothing'
end
fcnTest;
error when file doesn't exist before running

Repaired Function

function fcnBugRepair( id, mode)
% Repaired by adding clear statement in a good location
fid = fopen('.\fcnTest.m', 'w');
fprintf(fid, 'function fcnTest(varargin)\ndisp(''%s Problem'')', id);
fclose(fid);

clear fcnTest  % or could use rehash here instead

switch lower(mode)
    case 'clear+exist'
        clear fcnTest
        exist( 'fcnTest.m', 'file');
    case 'clear'
        clear fcnTest
    case 'nothing'
end
fcnTest;


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.

  • Loren: Paul- There *are* issues depending on the sizes of ii and jj. And it’s a bit complicated, but really...
  • Loren: Bob- You don’t say what happens when you run your code. Can you please explain more. It looks like you...
  • Loren: Kishore- It is not clear to me what you are trying to actually achieve. If you want to concatenate the 4...
  • Kishore: sorry, in the previous code mat2cell(c,[19 121],[19 134],[19 84],[19 107])
  • Kishore: Hi Loren, Why does the following not work? data_classwise = [19x121 double] [19x134 double] [19x84 double]...
  • Paul Jackson: Loren, Are there any aspects of empty matrices that may be tricky when they are used as indices into...
  • Bob: Hi Lori, Im trying to process Unicode text files from more than one different locales than the standard latin...
  • Loren: Ben- The reference link in my post documents the behavior of sum([]) and prod([]) (although the prod part only...
  • Ben: Loren/Andrey, A further advantage of having sum([])==0 and prod([])==1 is that it’s consistent with array...
  • Loren: OysterEngineer- I will SO take you up on that offer. Can’t wait for a good reason to visit now....

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