MATLAB: Inputting an output file name into a function

fopensprintf

HI,
I have a function:
function=tcaproc(mults,c2flag,filename)
where I do some math and then want to print to a file called filename.txt, for example, something like data1out.txt. I want to be able to change the filename is my point. So far I have tasted only abject failure.
formatSpec='%s.txt';
str=sprintf(formatSpec,filename)
file=fopen(str,'wt+');
just tells me that my filename doesn't exist.
test=tcaproc(as4,1,test1);
Undefined function or variable 'test1'.
I would appreciate your help.

Best Answer

When you do this:
file=fopen(str,'wt+');
you're getting an ID number (a "handle") to the file. So you'd do this:
function tcaproc(mults,c2flag,filename)
try
formatSpec='%s.txt';
baseFileName = sprintf(formatSpec, filename)
fullFileName = fullfile(pwd, baseFileName);
fileHandle= fopen(fullFileName ,'wt+');
% More code...... such as fprintf(fileHandle, '%s', someText);
% Handle any errors:
catch ME
errorMessage = sprintf('Error in function tcaproc.\n\nError Message:\n%s', ME.message);
fprintf(1,'%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
And you'd call it like this:
filenameInMainProgram = 'test';
tcaproc(multsInMainProgram, c2flagInMainProgram, filenameInMainProgram);