Clear Filters
Clear Filters

inputting an output file name into a function

7 views (last 30 days)
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.

Accepted Answer

Image Analyst
Image Analyst on 28 Dec 2012
Edited: Image Analyst on 28 Dec 2012
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);

More Answers (1)

Walter Roberson
Walter Roberson on 28 Dec 2012
test=tcaproc(as4,1,'test1');
  1 Comment
Matthew
Matthew on 2 Jan 2013
It was not quite that simple, but it was very close. The marked answer below was right on the money. THANKS TO ALL.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!