MATLAB: How to use set_param to set a Simulink block paramter to a value inside some structured data such as a matrix, cell array, structure, or table

set_paramsimulink

How do I use "set_param" to set a Simulink block paramter to a value inside some structured data such as a matrix, cell array, structure, or table?

Best Answer

For most numerical parameters, the "set_param" command requires the value to be given as a character array (called strings previous to R2016b), so we would have to enter '2' in place of 2 for example.
If we have some structured data and want a number from it, we cannot simply put single quotes around the command to get the value since this will give us the character array of the command itself not the underlying value we are trying to get. So for example, if we have a 2x2 matrix A and we want to assign some parameter to the number at A(2,2), we cannot use 'A(2,2)'.
The approach we can take is to use the "num2str" function to convert the output of A(2,2) to a character array, i.e. assign the parameter to num2str(A(2,2)).
Below is some example code which generates a Simulink model with a gain block between an inport and an outport, and sets the gain to have the value A(2,2) from a randomly generated matrix A.
%create a simulink model with an inport -> gain block -> outport
new_system
open_system untitled
add_block('simulink/Commonly Used Blocks/Gain','untitled/Gain');
add_block('simulink/Sources/In1','untitled/In1');
add_block('simulink/Sinks/Out1','untitled/Out1');
add_line('untitled','In1/1','Gain/1');
add_line('untitled','Gain/1','Out1/1');
Simulink.BlockDiagram.arrangeSystem('untitled')
%generate a matrix of values
A = randn(2,2);
%set the gain block to have a gain equal to the value at A(2,2)
set_param('untitled/Gain','Gain',num2str(A(2,2)));
Note that for other types of structured data the approach would be the same except we would substitute the appropriate command to access the value, e.g. myCellArray{1}, myStruct.Value, myTable{3,4}.