« Earlier7 items total Later »

Matlab onCleanup fatally flawed?

Matlab 2008a provides a new function

onCleanup

Loren Shure writes about it here http://blogs.mathworks.com/loren/

However I think the class is fatally flawed.

As I read the Matlab documentation the implementation of onCleanup is fatally flawed and I don’t think anybody should use it unless some things can be clarified.

According to the Matlab documentation

‘the lifecycle of an object ends *sometime* between the time its variable is no longer used inside the function and the end of the function’

The implementation of onCleanup seems to rely on a subtly different interpretation of object lifecyle.

‘the lifecycle of an object ends at the end of the function within which it’s last reference is lost’

This means the following example

function y = run4
% run4 processes an image file.
[fid,C] = openImageFile4();
blocksize = 100;
y = [];
while something
 dat = fread(fid,count);
 y = doSomething(y,dat);
 something = update(something);
end


is broken.

According to Matlab spec C could be deleted any time after it appears in the line

[fid,C] = openImageFile4();

thus deleting the file handle whilst it was being used. It looks like a classic race condition problem.

To be safe you could rewrite the code

function y = run4
% run4 processes an image file.
[fid,C] = openImageFile4();
blocksize = 100;
y = [];
while something
…dat = fread(fid,count);
…y = doSomething(y,dat);
…something = update(something);
end
C;


But somehow I see the Matlab optimiser at some time in the future stripping out such dead code and rendering the trick useless anyway.

Stylistically it is also not obvious to a reader of the code what C is being used for and it’s inclusion in the code could easily be deleted by an eager maintainer unless the ode is accompanied by copious documentation.

There are however neater ways to solve the same problem in other languages.

The Python way:

http://docs.python.org/whatsnew/pep-343.html


with open(/etc/passwd’, ‘r’) as f:
   for line in f:
      print line


lexical scoping is used to clarify the required lifetime of the file handle f. As well if any exception is thrown from within the block the file is also closed.

The Ruby way:

File.open ‘/etc/passwd’ do |f|
 f.each_line do |l|
   puts l
 end
end


Very similar to the python way and again there is no requirement by the user to provide any cleanup or close functionality. In case of normal block termination or in the event of an error the open function will *always* close the file handle when the block terminates.

The onCleanup functionality could also be dealt with by adding an ensure keyword to the Matlab language as has Ruby and Python.

function do_open(file, flags, action)
 fid = fopen(file, flags)
 try
   action(fid)
 ensure
   fclose(fid)
 end
end


Notice there is no catch above. We don’t want to catch an error we just want to *ensure* that we cleanup if there is an error or not. Any error is propagated to code further upstream to handle. The ensure can be substituted with a catch and rethrow but is a bit uglier as you need to write code to handle closing the file if and if not an error occurs.

Using do_open in Matlab would be like

do_open(/etc/passwd’, ‘r’, @body)
function body(fid)
 read(fid, 10)
 function_with_error()
end


As is obvious the function definition is kind of superfluous and would be nicer with some kind of multi line anonymous function

do_open(/etc/passwd’, ‘r’ ) @(fid)
 read(fid, 10)
 function_with_error()
end

C++ lambdas

I've just noticed that the C++0x standard has just accepted lambda functions as part of the upcoming standard. So you will be able to do


std::vector<int> someList;
int total = 0;
std::for_each(someList.begin(), someList.end(), <>(int x) : [&total] (total += x));
std::cout << total;


It actually comes in two forms, an expression form where a return value is not required for one line quickies and a function form which is surrounded by curly braces and requires a return statement.

Note that Matlab only allows the expression form. Multi line anonymous functions are not possible which is quite strange and limiting.

See to matlab lambda functions c++0x by bradphelan on Mon Mar 10 21:38:06 +0000 2008

Matlab 2008a

I don't do much Matlab these days but it is nice to see that release 2008a is out with the much waited for object oriented additions.

It is definitely something that will make programming Matlab much easier for larger applications and do away with many of the hacks which I have illustrated myself on this website. However I am not sure I like the verbosity of the OO features.

For example there are provisions for

- attributes
- events
- methods
- listeners

whereas in Ruby you can make do with just instance variables and methods, the rest being sorted out with meta programming tricks. Mentioning metaprogramming I don't see any facility for this within the documentation though it is probably there under the hood.

Also not sure why you are restricted to creating classes in files. It would be neat and generally usefully to be able to create classes at the command line and/or multiple classes per file as is possible in Ruby/Python.

I also noted a boo boo in the documentation. Some doc writer claims that Matlab is weakly typed, when in fact they mean dynamically typed as opposed the to statically typed.

Matalb is strongly and dynamically typed whereas C/C++ is weakly and statically typed.

A simple example from the Mathworks home page


classdef BankAccount < handle
   properties (Hidden)
      AccountStatus = 'open';
   end
% The following properties can be set only by class methods
   properties (SetAccess = private)
      AccountNumber
      AccountBalance = 0;
   end
% Define an event called InsufficientFunds
   events
      InsufficientFunds
   end
   methods
      function BA = BankAccount(AccountNumber,InitialBalance)
         BA.AccountNumber = AccountNumber;
         BA.AccountBalance = InitialBalance;
% Calling a static method requires the class name
% addAccount registers the InsufficientFunds listener on this instance
         AccountManager.addAccount(BA);
      end
      function deposit(BA,amt)
         BA.AccountBalance = BA.AccountBalance + amt;
         if BA.AccountBalance > 0
            BA.AccountStatus = 'open';
         end
      end
      function withdraw(BA,amt)
         if (strcmp(BA.AccountStatus,'closed')&& BA.AccountBalance < 0)
            disp(['Account ',num2str(BA.AccountNumber),' has been closed.'])
            return
         end
         newbal = obj.AccountBalance - amt;
         BA.AccountBalance = newbal;
% If a withdrawal results in a negative balance,
% trigger the InsufficientFunds event using notify
         if newbal < 0
            notify(BA,'InsufficientFunds')
         end
      end % withdraw
   end % methods
end % classdef


See Mathworks for more information.

select line by mouse motion

I'm trying to catch the lines the user selected by the mouse MOTION (i.e. NOT by clicking) WindowButtonMotionFcn and WindowButtonUpFcn are defined only on the figure that mean I can have only the "current point" value (but not current object for example..) and thats doesn't help me for identify the line the user have selected.
anyone can help me???

thanks
dalhad@gmail.com

Matlab & Ruby Together

Found a project on rubyforge that adds a Matlab interface to Ruby via the Matlab Engine. Check it out. Ruby is the language Matlab should be if it got it's act together. For Matlab programmers who have never seen Ruby then goto http://www.ruby-lang.org

LP.org is another Matlab free code repository

feel free to go to:
http://en.literateprograms.org/Category:Programming_language:Matlab

to comment and participate, it's a wikipedia-like literate-programming oriented web site,

garzol

Calling Matlab From Java

Here is a class I built as part of my matlab distributed computing tool. It uses Java 1.5 with generics and variable argument lists to create a reasonably simple interface to Matlab functions.

The function object is thread safe and blocks until matlab returns the result.



import com.mathworks.jmi.*;

import java.util.concurrent.*;

/**
 * Represents a blocking matlab function call. Adds the ability to call a matlab
 * function in a thread safe manner. The function call to execute the matlab
 * function takes a variabe length argument list.
 *
 * @author Brad
 *
 */
public class MatlabFunction<T> {

    private class Completion implements CompletionObserver {

        private T returnValue;

        private Semaphore semaphore = new Semaphore(0);

        /*
         *
         * @see com.mathworks.jmi.CompletionObserver#completed(int,
         *      java.lang.Object)
         */
        @SuppressWarnings("unchecked")
        public void completed(int arg0, Object arg1) {
            returnValue = (T) arg1;
            semaphore.release();
        }

        T getReturnValue() {
            try {
                semaphore.acquire();
                return returnValue;
            } catch (InterruptedException e) {
                return null;
            }
        }
    }

    /** The name of the matlab function */
    String function;

    /** Handle to the matlab object */
    Matlab matlab = new Matlab();

    /**
     * Create a thread safe blocking matlab function object
     *
     * @param function
     *            The name of the matlab function
     */
    public MatlabFunction(String function) {
        this.function = function;
    }

    /**
     * Execute the matlab function
     *
     * @param args
     *            Variable input arguments
     * @return the result of the matlab function.
     */
    public T execute(Object... args) {
        Completion completion = new Completion();
        matlab.feval(function, args, completion);
        return completion.getReturnValue();
    }

}


Use the class like

MatlabFunction<double []> f = new MatlabFunction<double []>("times");
double x[] = f.execute(10,20);


The function should return the value 20

Just remember that you can't call this from the Matlab command line. It will deadlock and hang your Matlab. This should only be run from a seperate thread not directly invoked by the Matlab thread.

If you get a ClassCastException when running this then Matlab is returning a datatype different to what you have specified in the generics specification. Use a debugger to figure out what kind of datatype is being returned by matlab.

« Earlier7 items total Later »




Sponsored by

Sole Central

Your one stop shop for Birkenstock and Crocs shoes and sandles.