Filter löschen
Filter löschen

inputting an output file name into a function

7 Ansichten (letzte 30 Tage)
Matthew
Matthew am 28 Dez. 2012
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.

Akzeptierte Antwort

Image Analyst
Image Analyst am 28 Dez. 2012
Bearbeitet: Image Analyst am 28 Dez. 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);

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 28 Dez. 2012
test=tcaproc(as4,1,'test1');
  1 Kommentar
Matthew
Matthew am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by