How to use function parameters to index into matrix using evalin in "MATLAB Function" Block

2 vues (au cours des 30 derniers jours)
In my base workspace, I have a 5x8 matrix called "GEN_STATUS".
In my Simulink model, I have the following "MATLAB Function" block:
function [y, z, x, GEN_STATUS] = fcn(u, rowIndex, columnIndex)
evalin('base', 'GEN_STATUS(1, 4) = 123') % this works
evalin('base', 'GEN_STATUS(rowIndex, columnIndex) = 456') % this does not
I would like to set a value in this matrix based on indices passed into my function but get the following error:
Unrecognized function or variable 'rowIndex'.
Error in 'Model/MATLAB Function' (line 19)
How do I resolve this error?

Réponse acceptée

MathWorks Support Team
MathWorks Support Team le 2 Fév 2023
Referring to the following line:
evalin('base', 'GEN_STATUS(rowIndex, columnIndex) = 456')
The code that runs in "evalin" is using only variables from the base workspace (defined by the first parameter 'base'). However, the variables "rowIndex" and "columnIndex" are only defined in the scope of the "MATLAB Function" block, not the base workspace. 
Therefore, the solution to this problem is to save these variables to the base workspace before running the "evalin" line. These variables can be set in the base workspace using "assignin" just before your your call to "evalin" in your 'MATLAB Function' block as follows:
assignin('base', 'rowIndex', rowIndex);
assignin('base', 'columnIndex', columnIndex);
evalin('base', 'GEN_STATUS(rowIndex, columnIndex) = 456');
Please refer to the following documentation pages for more information on "assignin" and "evalin" functions:

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by