Simulation doesn't see variable when called inside a function

I have a simulation which has 5 parameters passed from workspace and I want to tune those parameters in order to minimize a fitness function. In a script I define initial values of those parameters and pass them to a function, where I run the simulation and calculate fitness value based on simulation's output. My function looks like this:
function [fitness_value] = fitness(consts)
out = sim('zad4');
water = out.water.data(length(out.water.data));
demand = out.demand.data(length(out.demand.data));
energy = out.energy.data(length(out.energy.data));
fitness_value = vpa(water, 16)/(vpa(demand, 16) * vpa(energy, 16) * 10^(-8))
end
The problem is when in main script I name the array of parameters as "consts_0" and call my function with this array, simulation doesn't see variable "consts". What should I change in order to run simulation with the parameters passed to a function?
Main script:
T_Z_open = 40;
E_on = 40.2;
E_off = 42;
partially_on = 40.5;
partially_off = 40;
consts_0 = [T_Z_open, E_on, E_off, partially_on, partially_off];
fitness(consts_0)
consts_min = fminsearch(@fitness, consts_0)
Error message:
Error using fitness (line 3)
Invalid setting in 'zad4/Constant' for parameter 'Value'.
Error in zad2 (line 15)
fitness(consts_0) - Show complete stack trace
Caused by:
Error using fitness (line 3)
Error evaluating parameter 'Value' in 'zad4/Constant' - Show complete
stack trace
Error using fitness (line 3)
Unrecognized function or variable 'consts'. - Show complete stack
trace
Error using fitness (line 3)
Variable 'consts' has been deleted from base workspace.
Suggested Actions:
Undo the deletion. - Fix
Load a file into base workspace. - Fix
Create a new variable. - Fix
- Show complete stack trace

 Réponse acceptée

Fangjun Jiang
Fangjun Jiang le 19 Mar 2020
The problem is that in your model, the block 'zad4/Constant' is looking for the parameter 'Value', presummabley from the base workspace.
There are a few approaches. The easiest thing to do is to add this line in your function before sim()
assignin('base','Value',consts);

1 commentaire

Thank you, modifying your solution to assignin('base','consts',consts); worked.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Block and Blockset Authoring dans Centre d'aide et File Exchange

Produits

Version

R2019b

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by