0

I'm working on a project and I need to work with certain variables from the workspace and I only have their name as a char array.

To make an example, I have array

var_names = {'var1', 'var2', ... } 

and these variables are (among many others) in the workspace as structs with multiple attributes - value, class etc. (I believe these are Simulink generated but I am not absolutely certain).

To simplify, say I have the names {'var1', 'var2'} and I need to make a product of their values

prod = var1.Value * var2.Value 

I tried things like

var_names(1).Value * var_names(2).Value 

and similar more obvious attempts but none were successful. A note - the eval doesn't work because of the struct nature of the variables and I need something else.

6
  • Show how you used eval please. Commented Jul 21, 2018 at 7:52
  • 2
    If you can sort all variables in a master structure, you can access the variables like this: masterStruct.(var_names{1}). This is much faster than eval. Commented Jul 21, 2018 at 8:52
  • 1
    @Anthony Faster and safer Commented Jul 21, 2018 at 13:43
  • I used eval similarly as in your answer, Mad Physicist. I can't remember the exact use but the problem is it doesn't work with Simulink.Parameter. The strange thing is that the code I wrote works in another script I wrote to test it but when I copy the exact same code into the large function I'm working on fixing, it stops working, saying Error using eval, Undefined function or variable 'Nameofvar'. Also, for some reason, if I change the value of said variable manually, it works for the one var and then breaks at the next one. Commented Jul 23, 2018 at 9:06
  • If you could show a sample of the misbehaving code, we'd be able to help you. Commented Jul 23, 2018 at 12:27

1 Answer 1

2

The standard way to get a variable by name is using eval. The important thing is to make sure to evaluate the right text:

names = {'var1', 'var2'};
x1 = eval(names{1});
x2 = eval(names{2});
prod = x1.Value * x2.Value
Sign up to request clarification or add additional context in comments.

Comments

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.