Passing a pfile (requiring an input) into a function
20 views (last 30 days)
I am working with some MATLAB p-files, which encode several systems. I am not able to look inside the p-files, but I need to describe/plot/perform operations on the input/output for each one. The actions I need to perform are lengthy, but they are essentially the same for each p-file. I want to be able to call each p-file inside a function , but by passing in the name of the p-file as an input. I would like to be able to pass in the number of the p-file or system (they are all named like so 'system1', 'system2', etc. ) and receive the relevant output. However, when I try to pass the p-file in as an argument, it says not 'enough input arguments' - because it requires an input.
The p-files are typically evaluated like:
Output = System1(input);
I want to be able to say somehting along the lines of:
output = systemEval('1')
by defining a function like so:
function [ output ] = systemEval(system_number):
input = rand(100)
p_fileName = fprintf( 'System', num2str(system_number) ) ... or .... p_fileName = ['System', num2str(system_number)];
output = p_fileName(input)
I am wondering if there is a way to pass in the number of the system, attach the number with the standardized filename inside the function, in order to evaluate the p-file corresponding to that number. I can only seem to get a string/char value that seems to direct me to the place in memory where the p-file is stored ( I can call 'type(p_fileName) and it tells me it is a P-file).
Walter Roberson on 25 Oct 2020
You can use feval() with the file name as the first parameter.
However, I recommend that you instead use str2func() passing in the name (without the .p) which will construct a function handle, which can then be passed around or invoked upon inputs.
If the number of invocations is high, I would suggest you consider constructing a vector of function handles in advance and passing around the vector, and indexing the vector as needed