1

There are few variables in my matlab workspace, lets say a and b. eg: a = 1:5; b = 1:10;

I used who to get their names.

like listVariables = who;

now listVariables has the variable names a and b, but i dont know how to access their values so that I can do some mathematical operations on them.

5
  • I wouldnt recommend to do this at all, however, check the eval function of matlab (eval(listVariables(1).name)) Commented Jan 21, 2020 at 9:26
  • 2
    May I ask what the use-case is? I mean, why would you do mathematical operations on variables you do not know? Commented Jan 21, 2020 at 10:18
  • @NickyMattsson, I am using matlab filter design tool and it has an option to import the coefficients designed in the tool to the workspace. on these coefficients i want to do some fixed point conversion,scaling etc Commented Jan 21, 2020 at 11:09
  • 1
    Arent the variables names predefined, meaning they always will be the same? Commented Jan 21, 2020 at 12:32
  • The names can be changed during export. Maybe saving to mat and loading a strict is an option. Commented Jan 21, 2020 at 18:38

1 Answer 1

1

It looks like evalin is what your are searching for:

a_val = evalin('base', listVariables{1});
b_val = evalin('base', listVariables{2});

The advantage of evalin is that it can be executed from a function (out of the scope of the workspace).

Example:

In workspace:

a = 1:5; b = 1:10;

Content of my_fun.m:

function my_fun()

listVariables = evalin('base', 'who');

a_val = evalin('base', listVariables{1});
b_val = evalin('base', listVariables{2});

display(a_val);
display(b_val);

Result of my_fun() execution:

a_val =

     1     2     3     4     5


b_val =

     1     2     3     4     5     6     7     8     9    10

Note: there are cases in which evalin is useful, but it's not a good coding practice.

Sign up to request clarification or add additional context in comments.

1 Comment

exactly what i was looking for, Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.