I wish to rename a structure variable name without making copies of the same
I tried using eval, however, it seems to make a new copy of original structure instead of renaming it.
e.g.
load (matFileName, 'oldStruct');
eval(['newName=' 'oldStruct']);
clear oldStruct
Now in workspace, I have two struct variables
oldStruct and newName.
However I just want renamed struct, i.e
newName
Is there an elegant way of doing this???
--
Thanks,
Shal
> clear oldStruct
> Now in workspace, I have two struct variables
> oldStruct and newName.
Really? Directly after "clear oldStruct" the variable oldStruct is existing?
Although I cannot imagine why the name of the variable could be important, this should work:
Data = load (matFileName, 'oldStruct');
newName = Data.oldStruct;
Now the contents of newName is an efficient shared data copy.
Kind regards, Jan
Jan, I think Shal is trying to avoid there being two copies in memory at any one time, perhaps he is working with very large structs or has limited memory/address-space.
Data = load(matFileName, 'oldStruct');
% There is one copy in memory here
newName = Data.oldStruct;
% There are two copies in memory here
What if he just saves the old Struct as a .mat and simply loads it directly with an assignment statement to a new name? Would that eliminate the second copy?
Scott
No there are only one since Matlab uses copy-on-write mechanism, so data are shared if there is no change of the contents.
This example will illustrate. The Data pointers are the same for "a", "b" and "Data.f"
>> a = [1 2 3 5];
>> Data.f = a;
>> b = a;
>> format debug
>> a
a =
Structure address = 33c1aab8
m = 1
n = 4
pr = 39b34a90
pi = 0
1 2 3 5
>> b
b =
Structure address = 33c1ac58
m = 1
n = 4
pr = 39b34a90
pi = 0
1 2 3 5
>> Data.f
ans =
Structure address = 33c110c0
m = 1
n = 4
pr = 39b34a90
pi = 0
1 2 3 5
% Bruno
Yes Scott, you are correct.
@ Jan: clear oldStruct, was just to show that I have to clear this variable specifically before doing further processing. I wanted to avoid it if possible..
I am dealing with large data structure, e.g. reading video streams..
However, Scott what you mentioned
Data= load(matFileToRead, 'oldStruct');
puts 'oldStruct' as one of the fields to Data
which does not help me, since the rest of the code
access fields as
oldStruct.a1 and not as Data.oldStruct.a1
I see. Excellent.
Shal, Bruno's post is very convincing and I was unaware of the sharing mechanism.
Scott