Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
accessing a variable defined by a string

Subject: accessing a variable defined by a string

From: rocky99 Therminator

Date: 22 Feb, 2009 18:00:04

Message: 1 of 8

Hi everyone,

I have nine vectors of different lengths: black1, black2, black2, red1, red2, red3, green1, green2 and green3 . I would like to access a certain element of one of those vectors, specified by a String. For example if given the string string1='black1'; I'd like to be able to access the 500th element of black1 ==> black1(500) just with string1 (I mean without having to type black1(500) by hand in the command window) . So, I need a way to "convert" a string type to a variable type or something like this.

Thanks a lot for your help and have a good day!

ronenk

Subject: accessing a variable defined by a string

From: Eric Williams

Date: 22 Feb, 2009 20:31:02

Message: 2 of 8

"rocky99 Therminator" <ronenk@mail.com> wrote in message <gns3r4$sq$1@fred.mathworks.com>...
> Hi everyone,
>
> I have nine vectors of different lengths: black1, black2, black2, red1, red2, red3, green1, green2 and green3 . I would like to access a certain element of one of those vectors, specified by a String. For example if given the string string1='black1'; I'd like to be able to access the 500th element of black1 ==> black1(500) just with string1 (I mean without having to type black1(500) by hand in the command window) . So, I need a way to "convert" a string type to a variable type or something like this.
>
> Thanks a lot for your help and have a good day!
>
> ronenk

help eval

Note: most people here frown upon using "evil eval".

Subject: accessing a variable defined by a string

From: Jos

Date: 22 Feb, 2009 21:21:01

Message: 3 of 8

"rocky99 Therminator" <ronenk@mail.com> wrote in message <gns3r4$sq$1@fred.mathworks.com>...
> Hi everyone,
>
> I have nine vectors of different lengths: black1, black2, black2, red1, red2, red3, green1, green2 and green3 . I would like to access a certain element of one of those vectors, specified by a String. For example if given the string string1='black1'; I'd like to be able to access the 500th element of black1 ==> black1(500) just with string1 (I mean without having to type black1(500) by hand in the command window) . So, I need a way to "convert" a string type to a variable type or something like this.
>
> Thanks a lot for your help and have a good day!
>
> ronenk

First, avoid creating your variables like this. Use cells or structures, as in

black = {1:3, 1:5, 2:5}
val = black{1}(3)

To avoid eval in this case, I suggest you do (once):

save myuglyvariables.mat black1 black2 black3 black4
S = load('myuglyvariables.mat')

and use dynamic fields from now on

fn = 'black1' ;
S.(fn)(3)

hth
Jos

Subject: accessing a variable defined by a string

From: Bruno Luong

Date: 22 Feb, 2009 21:41:02

Message: 4 of 8

I propose an alternate solution. Save this into a file called workspace.m:

classdef workspace
    
    properties
        wstype % 'caller' or 'base'
    end
    
    methods
        % Create workspace object
        function obj = workspace(varargin)
            if nargin==0
                wst='caller';
            else
                wst = varargin{1};
            end
            if ~ischar(wst) || ...
               ~(strcmpi(wst,'caller') || strcmpi(wst,'base'))
                error('Usage: ws = workspace(''caller'') OR workspace(''base'')')
            end
            obj.wstype=wst;
            fprintf('Workspace (ws) usage: \n');
            fprintf(' ws.(name)(...) = value;\n');
            fprintf(' rhs = ws.(name)(...);\n');
        end
        
        function varargout = subsref(obj, s)
            if isstruct(s) && isfield(s,'type')
                switch s(1).type
                    case {'()' '{}'},
                        subs = s(1).subs;
                    case ('.')
                        subs = {s(1).subs};
                end
                for k=1:length(subs)
                    vname = subs{k};
                    val = evalin(obj.wstype,vname);
                    if length(s)==1
                        varargout{k} = val;
                    else
                        varargout{k} = builtin('subsref', val, s(2:end));
                    end
                end
                
            end
        end
        
        function obj = subsasgn(obj, s, value)
            if isstruct(s) && isfield(s,'type')
                switch s(1).type
                    case {'()' '{}'},
                        subs = s(1).subs;
                    case ('.')
                        subs = {s(1).subs};
                end
                for k=1:length(subs)
                    vname = subs{k};
                    if ischar(vname)
                        if length(s)==1
                            assignin(obj.wstype, vname, value);
                        else
                            tmp = evalin(obj.wstype, vname);
                            tmp = builtin('subsasgn', tmp, s(2:end), value);
                            assignin(obj.wstype, vname, tmp);
                        end
                    end
                end
                
            end
        end
    end
end

%% end of workspace.m

Now under command windows, try how it work by doing this:

ws = workspace;

ws.('red3') = [1:1000];
ws.('red3') (10) = pi;

red3(9:11)

%%%%%%%%%%%%%%
I think this short code is worth for FeX, what people think?

Bruno

Subject: accessing a variable defined by a string

From: vgood

Date: 22 Feb, 2009 21:54:01

Message: 5 of 8

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <gnsgpe$mvf$1@fred.mathworks.com>...
> I propose an alternate solution. Save this into a file called workspace.m:
>
> classdef workspace
>
> properties
> wstype % 'caller' or 'base'
> end
>
> methods
> % Create workspace object
> function obj = workspace(varargin)
> if nargin==0
> wst='caller';
> else
> wst = varargin{1};
> end
> if ~ischar(wst) || ...
> ~(strcmpi(wst,'caller') || strcmpi(wst,'base'))
> error('Usage: ws = workspace(''caller'') OR workspace(''base'')')
> end
> obj.wstype=wst;
> fprintf('Workspace (ws) usage: \n');
> fprintf(' ws.(name)(...) = value;\n');
> fprintf(' rhs = ws.(name)(...);\n');
> end
>
> function varargout = subsref(obj, s)
> if isstruct(s) && isfield(s,'type')
> switch s(1).type
> case {'()' '{}'},
> subs = s(1).subs;
> case ('.')
> subs = {s(1).subs};
> end
> for k=1:length(subs)
> vname = subs{k};
> val = evalin(obj.wstype,vname);
> if length(s)==1
> varargout{k} = val;
> else
> varargout{k} = builtin('subsref', val, s(2:end));
> end
> end
>
> end
> end
>
> function obj = subsasgn(obj, s, value)
> if isstruct(s) && isfield(s,'type')
> switch s(1).type
> case {'()' '{}'},
> subs = s(1).subs;
> case ('.')
> subs = {s(1).subs};
> end
> for k=1:length(subs)
> vname = subs{k};
> if ischar(vname)
> if length(s)==1
> assignin(obj.wstype, vname, value);
> else
> tmp = evalin(obj.wstype, vname);
> tmp = builtin('subsasgn', tmp, s(2:end), value);
> assignin(obj.wstype, vname, tmp);
> end
> end
> end
>
> end
> end
> end
> end
>
> %% end of workspace.m
>
> Now under command windows, try how it work by doing this:
>
> ws = workspace;
>
> ws.('red3') = [1:1000];
> ws.('red3') (10) = pi;
>
> red3(9:11)
>
> %%%%%%%%%%%%%%
> I think this short code is worth for FeX, what people think?
>
> Bruno

Well, Jos' solution is 2 lines.

Subject: accessing a variable defined by a string

From: Bruno Luong

Date: 22 Feb, 2009 22:02:45

Message: 6 of 8

"vgood " <no@spam.com> wrote in message <gnshhp$dfj$1@fred.mathworks.com>...
> "Bruno Luong" <b.luong@fogale.findmycountry> wrote in message
>
> Well, Jos' solution is 2 lines.

Right, but with all due respect to Jos, it's not what OP asked for.

Bruno

Subject: accessing a variable defined by a string

From: Jos

Date: 23 Feb, 2009 08:00:23

Message: 7 of 8

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <gnsi25$hd8$1@fred.mathworks.com>...
> "vgood " <no@spam.com> wrote in message <gnshhp$dfj$1@fred.mathworks.com>...
> > "Bruno Luong" <b.luong@fogale.findmycountry> wrote in message
> >
> > Well, Jos' solution is 2 lines.
>
> Right, but with all due respect to Jos, it's not what OP asked for.
>
> Bruno

What is the difference?

1) Create this function on the path
  function S = workspace
  % WS = WORKSPACE returns variables in the workspace as fields of the structure WS
  evalin('caller','save myuglyvariables.mat')
  S = load('myuglyvariables.mat')
  delete('myuglyvariables.mat') ;

2) Usage in the command window
  red1 = 1:3 ; red2=10:20 ; % etc.
  WS = workspace ;
  varname = 'red1' ;
  WS.(varname)(1)

Jos

Subject: accessing a variable defined by a string

From: Bruno Luong

Date: 23 Feb, 2009 08:31:03

Message: 8 of 8

"Jos " <#10584@fileexchange.com> wrote in message <gntl2n$p3p$1@fred.mathworks.com>...
> "Bruno Luong" <b.luong@fogale.findmycountry> wrote in message
>
> What is the difference?
>
> 1) Create this function on the path
> function S = workspace
> % WS = WORKSPACE returns variables in the workspace as fields of the structure WS
> evalin('caller','save myuglyvariables.mat')
> S = load('myuglyvariables.mat')
> delete('myuglyvariables.mat') ;
>
> 2) Usage in the command window
> red1 = 1:3 ; red2=10:20 ; % etc.
> WS = workspace ;
> varname = 'red1' ;
> WS.(varname)(1)
>

The diffrence are:

1. There is no need for save/load that operates on the full workspace, with contains large variables that are not in interested, and save the harddrive for spinning unnecessary.

2. After creating variables with target names, commands for accessing *directly* to variable names (plot(red2), mean(read2), std(red2), ...) are allowed. This might not be a big deal for some of us, but for many people this convenient way of accessing variables is the source for similar threads every few days in this news group.

Bruno

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us