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

4 次查看(过去 30 天)
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?

采纳的回答

MathWorks Support Team
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:

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by