Call a Function in Another Function, Prepare the Argument as a String

1 view (last 30 days)
Hi there!
I have a function that takes input of the following form:
myFun({'.\file1.dat','.\file2.dat'},{'DataIdentifier'},'option','optionvalue')
I would like to create the input in another function and tried with creating this a character array:
function [ ] = myCall
%%Setup
myDir = './';
myIni = 'file';
myFiles = 1:10;
myLevel = '.dat';
myInterest = '{''var1''}';
myOptions = '''xvariable'',''y''';
%%Run
allFiles = '';
for i = myFiles
allFiles = [allFiles ''',''' myDir myIni '0' char(string(i)) myLevel];
end
myString = ['{''' allFiles(4:end) '''}'];
myFun(myString,myInterest,myOptions)
end
Now, myFun returns
Error using fgets
Invalid file identifier. Use fopen to generate a valid file identifier.
Is there a general limitation in passing character arrays or strings as input to a function in MATLAB? Because, when I copy myString and paste it into myFun in the Command Window, it works.
Thank you very much in advance for your help on that matter! :)

Accepted Answer

Stephen23
Stephen23 on 4 Feb 2021
Edited: Stephen23 on 5 Feb 2021
"Is there a general limitation in passing character arrays or strings as input to a function in MATLAB?"
No, but the way you are calling that function is nothing like how you say it should be called.
How it should be called:
myFun({'.\file1.dat','.\file2.dat'},{'DataIdentifier'},'option','optionvalue')
% ^^cell^array^of^char^vectors^,^^^^^^^ditto^^^^^^,^^^name-value^pairs^^^
How you are effectively calling it:
myFun('{''.\file1.dat'',''.\file2.dat''}','{''DataIdentifier''}','''option'',''optionvalue''')
% ^^^^^one^character^vector^here^^^^^,^^^^second^char^vec^^^,^^^^third^char^vector^^
You are trying to turn all of the inputs into character vectors which look a bit like input arguments, but in fact you should just create those cell arrays exactly as they should be provided to the function (i.e. as cell arrays, do NOT turn them into character vectors which look a bit like cell arrays (that in turn look like they contain character vectors...)).
function [ ] = myCall
%%Setup
myDir = './';
myIni = 'file';
myLevel = '.dat';
myInterest = {'var1'}; % !!! actual cell array !!!
myOptions = {'xvariable','y'}; % cell array -> used for comma-separated list.
%%Run
N = 10;
C = cell(1,N); % !!! preallocate actual cell array !!!
for k = 1:N % using SPRINTF and FULLFILE is much better than string concatenation:
C{k} = fullfile(myDir,sprintf('%s%02d%s',myIni,k,myLevel));
end
myFun(C,myInterest,myOptions{:})
% ^ actual cell array of character vectors
% ^^^^^^^^^^ actual cell array of character vectors
% ^^^^^^^^^^^^^ comma separated list:

More Answers (0)

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!