1

I am loading a loop in which different variables are loaded in every iteration. Name of each variable is different in each iteration. Is there anyway in Matlab to automatically access the value of that variable. So far I have tried like that:

for i=1:4
    str_load=strcat (fold_str, 'class_',class{:,i}, \Feeds_',files{:,i},'.mat');
    load(str_load)
    variables = who;
    var = strncmpi(variables,'Feed_A',6);
    chk=find(var==1);
    org_var=variables(chk,:);

end

I can have the name of the targeted variable in org_var. But How can I access values inside that?

1 Answer 1

3

The eval function would evaluate the variable name and return its value:

value = eval('org_var');

But a better solution would be to capture the output of load:

data = load(str_load);

Instead of loading all the variables into your workspace (and potentially changing any of the variables you need in your loop), it loads them in a struct data. Now you have:

value = data.Feed_A;

You can also do

variables = fieldnames(data);

and if the variable name you need is in a string,

var = 'Feed_A';
value = data.(var);
Sign up to request clarification or add additional context in comments.

3 Comments

org_var is a cell and it contains the name of variable 'Feed_A'. When I used value = eval('org_val'). It shows me the same variable name inside value 'Feed_A'. Can't have the data of Feed_A variable
When I try the loadbut how can i make it general because every file will load have different variable to use such as Feed_A, Feed_B, etc
@AadnanFarooqA: Updated the answer with some more ideas. I'm sure you can compose these into what you're looking for.

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.