jarhead
jarhead

Reputation: 1901

changing variable name matlab

I want to change a variable name before I export it to the global enviroment, the data is very large, meaning I can not copy it to another variable and delete the first one.

the data is loaded to certain variables and that I cannot change as well, it is used multiple times in differnet background jobs, so what I want to do is rename it and send it renamed so the jobs won't mix and after for the next job load and rename again etc.

basically is to do in the command window what I can do with the mouse in the workspace....

does anyone knows how to do it?

Upvotes: 15

Views: 33697

Answers (2)

stanri
stanri

Reputation: 2972

When assigning variable names, matlab uses a "lazy copy", so there is no reason why:

new_name = old_name;
clear old_name;

shouldn't work.

Upvotes: 16

learnvst
learnvst

Reputation: 16195

The only way that I can think of to do this without a memory copy would be to wrap the original data in an object that is a subclass of the handle class.

http://www.mathworks.co.uk/help/techdoc/matlab_oop/brfylzt-1.html

You can then 'copy' the handle class using normal syntax

 classB=classA

..but you are only making an alias for the same data (changes to classB are reflected in classA). This is the closest thing in matlab to pointer-like semantics.

For example, create a file called myHandle and paste the following text to define the class . .

classdef myHandle < handle

    properties
        data
        moreData
    end

    methods
    end

end

You can then use this just like a regular structure. From the command line do ..

>> x = myHandle

x = 

  myHandle handle

  Properties:
        data: []
    moreData: []

  Methods, Events, Superclasses

... we can then populate the data . . .

>> x.data = [1 2 3 4];
>> x.moreData = 'efg';

... once the original object has been populated with data, an alias of the original data can be made by typing . .

>> y = x

The interesting thing happens to x when y is modified, i.e.

>> y.data = [33 44 55 66];
>> disp(x)
x = 

  myHandle handle

  Properties:
        data: [33 44 55 66]
    moreData: 'f'

  Methods, Events, Superclasses

You can even clear one of the alias names . .

 clear x

..and the data will still be available in the other handle for the data, y. The memory is only freed when there are no more handles referring to it (when the reference count has reached zero).

Upvotes: 2

Related Questions