Easyquestionsonly
Easyquestionsonly

Reputation: 103

Variable replacement in tables with two loops

I wish to change variable names in a loop. The name is written in some cell array, like here:

http://imgur.com/szqGzkH

ML.species1{1:end,end+1}=0;
i=1:height(ML.species1);
        ML.species1{i,end}=(ML.species1.someindex(i)*3+(ML.species1.someotherindex(i)
end

I can't just call the name of the variable and say ML.(ML.speciesname{1,1}){i,end}=... why not?

and if that should work, id like to make a second loop around the basic calculation, just exchanging the variables here ML.speciesname{1,j} one by one by moving my index j to column name 2, 3 ... How does that work?

Upvotes: 0

Views: 101

Answers (2)

Floris
Floris

Reputation: 46375

Still not 100% sure what you are trying to do - but I believe the following should help:

You can access an element in a structure in different ways:

ML.element1='hello world';
fieldName = 'element1';
disp(getfield(ML, fieldName));

As you can see, using getfield I can access an element even if I don't know the name of the element at the time I write the code (as long as I have the name in a variable).

Similarly, you can use setfield to create an element:

setfield(ML, fieldName, 'goodbye world');
disp(ML.element1);

update - if you want to index an element of a specific (variable) field name, you could do the following:

fieldname = 'one';
ML.(fieldname) = [123 234];
ML.(fieldname)(3) = 456;
disp(ML)

ML = 

  one: [123 234 456]

Note - the trick is in the () parentheses around the (variable) name of the field.

Upvotes: 2

buzjwa
buzjwa

Reputation: 2652

You might find the eval function useful for using strings to define variable names and values. For example if you have a name you want to give a variable in strVarName (a string) and a value for it in dValue (a double), you can write:

eval([strVarName ' = ' num2str(dValue) ';']);

Documentation for eval.

Upvotes: 2

Related Questions