m_power
m_power

Reputation: 3194

Dynamically persistent variable

I have a function that use 2 persistent variable. The function input is gcb, for the actual simulink block. I want to use the function on various block, hence I would like to have the persistent variables declared with a name that makes reference to the block name.

function testBlock(blk)
    blkName = get_param(blk, 'name')
    persistent blkValues % this works for one block
    % but I want something like this
    persistent eval([blkName 'Values']) % doesn't work
    ...
end

Upvotes: 1

Views: 494

Answers (2)

macduff
macduff

Reputation: 4685

If all you wanted to do is store the name of the block, then yes. If you wanted some data and a descriptive name, I would think a structure would work like:

data = struct([blkName 'Values'],[]);
set_param(gcb,'UserData',data);

Then when you get the data you use,

ud = get_param(gcb,'UserData');
% ud.([blkName 'Values']) <- your data

Or you could use the global appdata storage:

setappdata(0,[blkName 'Values'],data);

data = getappdata(0,[blkName 'Values']);

Or you could rewrite the function at runtime to create a variable with the name you want, yick, but I've seen similar things done. HTH!

EDIT The UserData is the method I have used many times for a dialog callback, so I feel confident that it will work, however I may not completely understand your application. :-)

EDIT If you need the data to persist each time you load the model, then you must set the UserDataPersistent parameter to 'on'. This is an annoying, but understandably necessary feature to choose whether to forget about what happened after the model is closed and flushed out of memory. Since this is your use case, persistent variables in an m-script will not work since they are forgotten when Matlab terminates. I believe you would need to use like a setpref to get it to persist between Matlab sessions.

Upvotes: 1

Navan
Navan

Reputation: 4477

function with persistent data and reusing that function at different places for different purposes is mutually exclusive. You cannot do both. You have to put your data outside the function. Some ways for doing this are, a)the already suggested UserData field, b)an external file for e.g. a mat file, or c) a container like a map to look up based on the input.

Upvotes: 1

Related Questions