Path: news.mathworks.com!not-for-mail
From: "Steven Lord" <slord@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to rename a workspace variable in a loop?
Date: Wed, 17 Dec 2008 12:53:47 -0500
Organization: The MathWorks, Inc.
Lines: 61
Message-ID: <gibebb$ft8$1@fred.mathworks.com>
References: <f7olca$1mj$1@fred.mathworks.com> <f7om7m$dvb$1@fred.mathworks.com> <gi9c71$c2a$1@fred.mathworks.com> <WlX1l.5935$%z5.391@newsfe09.iad> <gib8ib$p3p$1@fred.mathworks.com>
Reply-To: "Steven Lord" <slord@mathworks.com>
NNTP-Posting-Host: lords.dhcp.mathworks.com
X-Trace: fred.mathworks.com 1229536427 16296 144.212.105.187 (17 Dec 2008 17:53:47 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 17 Dec 2008 17:53:47 +0000 (UTC)
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.5512
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5579
X-RFC2646: Format=Flowed; Original
Xref: news.mathworks.com comp.soft-sys.matlab:507577


"Matt" <mjacobson.removethis@xorantech.com> wrote in message 
news:gib8ib$p3p$1@fred.mathworks.com...
> Walter Roberson <roberson@hushmail.com> wrote in message 
> <WlX1l.5935$%z5.391@newsfe09.iad>...
>> Matt wrote:
>>
>> > I''m in a situation where it would be really great to be able to save a 
>> > large array X to a .mat
>> > file but later to load back only pieces of X into the workspace. 
>> > Imagine for instance that X
>> > is a large 3D image and later you want to load in one slice at a time 
>> > for some sort of
>> > slice-wise processing.
>>
>> > Unfortunately, load() doesn't let you do this. So, the only alternative 
>> > I can come up with
>> > is to save each slice of X to the .mat file as an individual variable, 
>> > dynamically
>> > created using eval().
>>
>> Nope.
>>
>> S = 
>> cell2struct(mat2cell(X,size(X,1),size(X,2),ones(1,size(X,3))),num2str((1:size(X,3)).','slice%d'),3);
>> save(OutputFileName,'S', '-struct');
>>
>> Or use dynamic field names in building up S and then use the save -struct 
>> approach.
>
> Well, okay. If you're point was that you don't need to use eval(), then 
> yes.

If you don't like Walter's two-liner, try:


for k = 1:size(X, 3)
    S.(sprintf('slice%d', k)) = X(:, :, k);
end
save(OutputFileName,'S', '-struct');


Yes, it has a FOR loop.  Unless your X has a lot of pages, though, the FOR 
loop won't have to execute for very long.  And IMO it's more easily read 
than Walter's two-liner.

> My point was more that this is an application requiring that arrays be 
> assigned to dynamically named variables. The use of arrays, as encouraged 
> by the FAQ, is not enough
> here.

The use of an array is insufficient in this case.  The use of a combination 
of dynamic field names and the -struct flag for SAVE is sufficient to 
accomplish the goal as you stated:  "later you want to load in one slice at 
a time for some sort of slice-wise processing."

-- 
Steve Lord
slord@mathworks.com