Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Using functions and structures sensibly
Date: Thu, 8 May 2008 15:30:55 +0000 (UTC)
Organization: Mitre Corp
Lines: 74
Message-ID: <fvv6bf$4gd$1@fred.mathworks.com>
References: <fvuu3s$bd$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1210260655 4621 172.30.248.37 (8 May 2008 15:30:55 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 8 May 2008 15:30:55 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2318
Xref: news.mathworks.com comp.soft-sys.matlab:467420



"Pete " <pete.dot.bankhead@btinternet.dot.com> wrote in 
message <fvuu3s$bd$1@fred.mathworks.com>...
> Hi,
> 
> I have some code that works, but I want to check whether 
I'm doing 
> something horribly inefficient or unwise based upon how 
MATLAB deals with 
> function arguments.
> 
> Basically, I have a (reasonably) large structure, which 
has been preallocated 
> with all the correct fields.
> I want to pass it to some functions (it isn't certain in 
advance which functions) 
> that will modify some fields of the structure.
> 
> A dramatically shortened version of the code might be:
> 
> % preallocate structure
> S = struct( [field names and initial values] );
> % apply functions
> for ii = 1:numel(fh)
> 	S = feval(fh{ii}, S);
> end
> 
> where fh is a cell array containing the names of certain 
functions stored in M 
> files which begin something like,
> 
> function myStruct = myFunction(myStruct)
> 
> I read something that suggested modifying input arguments 
in MATLAB 
> functions is bad most of the time.

The only reason why I know modifying inputs "is bad" is 
that MATLAB will pass the inputs by value (instead of by 
reference).  But, one way or another, you are creating 
another copy of myStruct anyway.

>  I also wasn't sure about using the same 
> variable name for both the input and the output, but in 
my mind this seems 
> sensible for what I want to do.

You could use something like:

function myStruct = myFunction(myInpStruct)
myStruct = myInpStruct;
...

and call it exactly the same way:

myStruct = myFunction(myStruct)

But, I don't know that this is any more efficient.  (Might 
make it easier to debug MyFunction.)

> Is it sensible, or will it result in unnecessary 
overhead?  Would others here do 
> things the same way or differently?
> 
> Currently my code seems to work well and fast enough, but 
if it is bad 
> practice and there is a better way then I'd like to learn 
it.  I'm using 2007b at 
> the moment, and the code is part of a gui created using 
GUIDE.
> 
> Thanks,
> 
> Pete