Change value of one element of a vector valued Simulink Constant Block
5 views (last 30 days)
Show older comments
I would like to programmatically change one element of a vector valued Simulink Constant Block.
So for example suppose I have a constant block whose value is currently assigned the vector value [3,1,5] and I wish to change the second element from 1 to 6 so that the constant block will have the value [3,6,5].
I assume that I will need to use set_param for this purpose. The difficulty is that the Value parameter of a constant block must be set as a string, and it seems you would have to enter the entire string, describing the vector of values.
For example, I can use set_param to change the whole vector of values
set_param(gcb,'Value','[3,6,5]')
but is there some way to directly change just the second element?
The only thing I've been able to come up with requires mulitple lines of code and seems quite awkward:
valstr = get_param(gcb,'Value'); % get Value as a string, e.g. '[3 1 5]'
val = str2num(valstr(2:end-1)); % remove left and right brackets and convert to a numerical array
val(2) = 6; % assign new value to second element
valstr = mat2str(val); % convert to string with left and right brackets, e.g. '[3 6 5]'
set_param(gcb,'Value',valstr) % assign new value
If anyone has a cleaner way of doing this I would appeciate it. Otherwise, of course I could put those 5 lines of code into a little function, and call it when needed, but it seems like a hard way to go.
Thanks for your assistance
2 Comments
Paul
on 28 Jul 2020
I don't think there is a cleaner way because Value can be any valid Matlab expression. I will be very interested if someone comes up with a better solution.
You don't need that line to remove the brackets from valstr. str2num should work on valstr directly for your use case where valstr is a vector expressed in char format.
>> valstr = '[1 3 5]';
>> str2num(valstr)
ans =
1.00 3.00 5.00
Answers (0)
See Also
Categories
Find more on String in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!