Max
Max

Reputation: 1481

Use exist to check if Simulink-Block has parameter 'SampleTime'

I want to write a function that automatically changes the parameter SampleTime of all blocks in my model to a specific value. I can use find_system to find all blocks and then I can loop through all blocks and use set_param('Blockpath','SampleTime','0.001'). But if I do this and the block does not have a parameter called SampleTime, it'll make my program crash.
So my question is how can I find out if the parameter exists before setting it? I tried something like exist(['blockpath','/SampleTime']), but it didn't do what I expected. Any ideas?

Upvotes: 1

Views: 4278

Answers (2)

Phil Goddard
Phil Goddard

Reputation: 10772

Building on @Daniel's answer, if you really must do this, which for reasons given in the comments to @Daniel's answer is a bad idea, then the simplest approach is

% Define the new value as a string
>> newSampleTime = '10';
% Find all blocks in the model
>> allBlocks = find_system(gcs);
% Identify the blocks that have a SampleTime property
>> blockIdx = cellfun(@(c)isfield(get_param(c,'ObjectParameters'),'SampleTime'),allBlocks);
% Change the sample time
>> cellfun(@(c)set_param(c,'SampleTime',newSampleTime),allBlocks(blockIdx));

Upvotes: 1

Daniel
Daniel

Reputation: 36710

You can use get_param('blockpath','ObjectParameters') to get a struct with all parameters and then use isfield to check if you can find SampleTime.

I think what you are doing is not a good idea. In typical simulink models, you have the sample time set only at very few places, running all other models with inherited sample time. In most cases, it is not a problem to change these few places.

If you have to many blocks or you frequently change the sample time, better use a workspace variable or a mask parameter. Set all blocks to to have sample time x and put x=0.01 in your base work space to set it for all blocks.

Upvotes: 5

Related Questions