1
votes

I want to set the gain(value of K) in the simulink block when this model is simulating.

enter image description here

I created a GUI contains a button and an edit text(tagged "text_box"), and the callback function of this button will set the gain by specifying the K in base work space.

% --- Executes on button press in FK_button.
function FK_button_Callback(hObject, eventdata, handles)
% hObject    handle to FK_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global K;

text=get(handles.text_box, 'String');
value = str2double(text);

K = value;

However, the simulink block only read the value of K in work space when I started simulation. During the simulation, if I press the button, the K value in base work space would change to the value I set, but the value of K in simulink wouldn't change.

I've also tried using set_param API to change the K in simulink by

% --- Executes on button press in FK_button.
function FK_button_Callback(hObject, eventdata, handles)
% hObject    handle to FK_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global K;

text=get(handles.text_box, 'String');
value = str2double(text);

%gui_variable is the model file name
set_param('gui_variable/Gain','Gain', value);

But I'll got error saying:

Error using robotics_gui_2>FK_button_Callback (line 429)
Invalid setting in Gain block 'Gain' for parameter 'Gain'

What can I do to alter K in simulink during simulation?

1

1 Answers

4
votes

You need to call set_param to update the value used by Gain block. It does not automatically read new values from MATLAB workspace. The value you pass to set_param is a string. So you do not need to convert it to double before using it in set_param. You can also use set_param('gui_variable/Gain','Gain', 'K') which will make set_param read new value of K from workspace.