Question

I'm working on a project in Matlab in which I have to modify a pre-existing code.

Before starting to work, I'd like to understand how eval function is used.

First of all, there's the parameter struct definition (look at eval function):

function [ descriptor ] = parameter ( name, nominal, mode, range )

descriptor = struct (              
    'name',         name,       % Parameter name inside Simulink schematic
    'nominal',      nominal,    % Nominal parameter value
    'mode',         mode,       % Range mode name in { 'Range', 'Percentage', 'PlusMinus' }
    'range',        range       % Range boundaries, 1x2 vector
);
eval([ name '=' num2str(nominal) ';' ]);  % Initialize with nominal value

end

Just for completion, parameter cell array is defined as follows:

parameters = {};                         % Simulation parameter declarations

parameters{end+1} = parameter( 'simulink_Imm(1,1)', simulink_Imm(1,1), 'Percentage', [-10, 10] );

parameters{end+1} = parameter( 'simulink_q0(1)', 0, 'Range', [-1, 1] );
etc...

Finally we have this for loop (always look at the eval function):

for i = 1 : numParameters
    p = parameters(i); p = p{1};
    value = urealvalue( p.nominal, p.mode, p.range );   % Generate random real value
    eval([ p.name '=' num2str(value) ';' ]);      % Assign the generated value

That function is used twice and honestly I don't get how it works. I understand what it does thanks to the comments, but I don't understand how it assigns values.

I also searched in the matlab documentation, but it doesn't help.

Can anybody shed some light on this?

Was it helpful?

Solution

eval evaluates a valid Matlab expression which is defined by a string.

Imagine the following:

name = 'myVar';
nominal = 42;

when you now call:

eval([ name '=' num2str(nominal) ';' ]);

which is the same like:

eval([ 'myVar = 42;' ]);

you get a variable myVar in your workspace which has the value 42.

The same happens, when you type in

myVar = 42;

directly. So instead of having a line of code in your script, you can just evaluate a code-string from wherever. In your case it is used to create a variable from two struct fields, the first the variable name and the second it's value.


Another example, you want a variable named after it's actual value. But you don't know its name before:

value = randi(10);
eval([ 'var' num2str(value) '=' num2str(value) ';' ]);

The only way to do this is by using eval as you need to create a code-line-string according to the random generated value. Eval then "writes" it. If for example value = 9, it is stored to a variable var9 in the next step.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top