File Exchange

image thumbnail

Inplace

version 1.0.0.0 (56.9 KB) by David Gleich
Allows Matlab variables to be passed by reference instead of by value allowing inplace modification.

2 Downloads

Updated 06 Jun 2006

No License

Inplace is a Matlab package for working with matrices and vectors that are passed by reference instead of by value. This package allows variables to functions to be modified inplace. Previously, this behavior was not possible in Matlab.

To install, see the installation section of the documentation page: http://www.stanford.edu/~dgleich/programs/inplace/

It provides two classes, ipdouble and ipint32 (inplace double and inplace int32) that wrap Matlab's double and int32 matrices and vectors. The idea behind the package is simply to provide a way to modified arguments to a function directly without the necessity of returning the result and the hence, eliminating a copy required.

Example:
function a=func1(a)
a(1) = a(1)+1;
function func2(ipd)
ipd(1) = ipd(1)+1;
a = ones(5,1);
ipd = ipdouble(a);
a = func1(a);
func2(ipd); % accomplishes the same result without the copy at the end of the function.

Comments and Ratings (7)

Jveer

why not just use global variables?

Matthew

David Gleich

I agree with Danilo that the nested function example is faster in this case. However, it is a little more cumbersome to program.

Perhaps I will try to write a new version of the inplace library based on function closure idea you illustrated. (Send me an email if you are interested in helping.)

Danilo Zanatta Filho

Very good function !!!!
There is a way to do the same in pure Matlab though:

function example()

a = ones(n,1);

function add_one_return_local()
a(1) = a(1) + 1;
end

add_one_return_local;

end

Since "add_one_retunrn_local" is nested in the "example" function, it has acces to its (example's) workspace.

I know it doesn't cover all the cases, but it's faster than using Inplace in this case...

David Gleich

I tested the example given by Raymond and it works correctly on my version of Matlab. If someone else notices that it does not work, please send me an email directly.

Raymond Norris

David-

What about the case:

a = ipdouble(3);
b = 3;
a(1) = 4
b

Since 'b' is a shared copy of 'a', b also gets modified. Is that the intended behavior? If not, you need to check how many references of 'a' there are (there is an undocumented API for this) and then break the link (which in essence what you're trying to avoid in the first place) so as to not modify 'b'.

Raymond

Jeremy Kozdon

This is pretty amazing. I always wondering if there was a way to speed up operations like this in MATLAB, which I have felt were a little too inefficient. Now I know, and someone has written the software to do it.

MATLAB Release Compatibility
Created with R14
Compatible with any release
Platform Compatibility
Windows macOS Linux