Add rows to txt file in order to create a matrix

2 visualizaciones (últimos 30 días)
dilo88
dilo88 el 31 de En. de 2013
Hello,
I implemented a code in matlab that gives me all the possible permutations of a 10-element vector with some peculiar features (all elements must be between 0 and 1 and the sum of all elements equal to 1).
I would like to export each permutation (1x10 matrix) I obtained to a txt file, in order to create a big matrix (# of permutations x 10) with all these permutations. The process should be: obtain the first permutation from my code, export this permutation (1x10 matrix) to the txt file as a new row, do it again for the next permutation I obtain and so on, save the matrix of all the permutations and use it again in matlab for other purposes.
Could someone help me with this issue?
If possible, I need an efficient way to do this since I have many permutations to export to the txt file. I do not know the total # of permutations.
Thank you.
Claudio

Respuesta aceptada

José-Luis
José-Luis el 31 de En. de 2013
Editada: José-Luis el 31 de En. de 2013
Saving the permutations one by one as they are generated sounds very inefficient due to i/o overhead. It is probably best to save all your permutations once you have them, or if the number is really large, use some buffer that you would save when filled. One way of appending data to a file is:
delete bla.txt %Get rid of this line if you want to start appending from the get go
fid = fopen('bla.txt','a');
for ii = 1:10
your_data = rand(1,10); %or however you generate it
fprintf(fid,'%f ', your_data);
fprintf(fid,'\n');
end
fclose(fid);
Please accept an answer if it helps you.
  2 comentarios
dilo88
dilo88 el 1 de Feb. de 2013
Thanks José-Luis, it works perfectly!
Claudio
José-Luis
José-Luis el 1 de Feb. de 2013
My pleasure.

Iniciar sesión para comentar.

Más respuestas (1)

Shashank Prasanna
Shashank Prasanna el 31 de En. de 2013
You can keep this in a loop and use it as many times:
dlmwrite('test.txt', rand(1,10), '-append','delimiter',' ')
rand(1,10) if you permutations each time.

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by