Clear Filters
Clear Filters

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

3 views (last 30 days)
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?

Accepted Answer

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

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!