Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

call recursive fun. erase txtfile

Asked by huda nawaf on 7 Sep 2012

hi, I i have recursive function , each time call this function return different array.

I want to print these arrays into txt file, it is important to me store all arrays. But the problem each time is called function will erase the txtfile.

What I have to do to save all arrays?

THANKS IN ADVANCCE

0 Comments

huda nawaf

Tags

Products

No products are associated with this question.

2 Answers

Answer by Jan Simon on 7 Sep 2012
Edited by Jan Simon on 7 Sep 2012
Accepted answer

Main function, which opens and closes the file:

fid = fopen(FileName, 'w');
if fid == -1, error('Cannot open file'); end
Recursive(fid, 17);
fclose(fid);

And the recursice function:

function Recursive(fid, Num)
Num = Num - 1;
if Num == 0
  return;
end
fprintf(fid, '%d\n', Num);
Recursive(Num);
end

Or you open the file in the recursive function for appending:

function Recursive(Num)
fid = fopen(FileName, 'a');
if fid == -1, error('Cannot open file'); end
fprintf(fid, '%d\n', Num);
fclose(fid);
Num = Num - 1;
if Num > 0
  Recursive(Num);
end

4 Comments

Jan Simon on 10 Sep 2012

You think that the code will erase the formerly written data? I suggest to try it instead. fopen(FileName, 'a') opens a file for appending...

huda nawaf on 13 Sep 2012

thanks i will try

huda nawaf on 14 Sep 2012

thanks jan, it is working now

Jan Simon
Answer by Azzi Abdelmalek on 9 Sep 2012

maby your fclose(fid) is in the loop

fid = fopen('filename.txt', 'w');
for k=1:10
  v=(1:k), %example 
fprintf(fid, '%f\t',v);
fprintf(fid, '\n',[]);
end
fclose(fid);

5 Comments

Azzi Abdelmalek on 9 Sep 2012

if you post your function, it will be helpfull

Azzi Abdelmalek on 9 Sep 2012

I think you can add this code inside your function just after cluster1

fprintf(fid, '%f\t',cluster1);
fprintf(fid, '\n',[]);

and call your function

fid = fopen('filename.txt', 'w');
F=devide();
fclose(fid);
huda nawaf on 11 Sep 2012

thanks, do u mean open file in main program?

I will try do that. if I failed , I will send my code.

thanks again

Azzi Abdelmalek

Contact us