Borrar filtros
Borrar filtros

How to write a new column in a text file?

19 visualizaciones (últimos 30 días)
Cretu Ioana
Cretu Ioana el 24 de Abr. de 2020
Comentada: Ameer Hamza el 24 de Abr. de 2020
I have a text file which already has two columns (one with pressure values, the other one with velocity values). I want to make a new column on the right side in which I add the time. If I use this code, it adds me the column, but below my existing columns. I want them to be like this: 'Pressure Velocity Time.'
string='E:\MASTER\Biofluid mechanics\WIA-Matlab-Biofluid\data2.txt';
fid=fopen(string,'a');
x=[0:0.005:.625]; %time
x=x';
fprintf(fid, '%f\n',x)
fclose(fid);

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 24 de Abr. de 2020
Editada: Ameer Hamza el 24 de Abr. de 2020
The easiest way is to load the entire file and then save it again after adding the third column. Any other option will require you to use fseek to move row by row and write each number at a time at a specified location.
string='E:\MASTER\Biofluid mechanics\WIA-Matlab-Biofluid\data2.txt';
data = load(string); % load data in txt file
x=[0:0.005:.625]; %time
data = [data x.']; % append the third column
fid=fopen(string, 'w');
fprintf(fid, '%f\t%f\t%f\n',data(:,1), data(:,2), data(:,3));
fclose(fid)
  2 comentarios
Cretu Ioana
Cretu Ioana el 24 de Abr. de 2020
Editada: Cretu Ioana el 24 de Abr. de 2020
Is working, thank you!
Ameer Hamza
Ameer Hamza el 24 de Abr. de 2020
Glad to be of help.

Iniciar sesión para comentar.

Más respuestas (1)

Geoff Hayes
Geoff Hayes el 24 de Abr. de 2020
Cretu - when you open the file with the 'a' permission, the data will be appended to the end of the file. Since you want to add a new column to the existing data, then you may want to first import the data into MATLAB, add the new column, and then write the data back to file. For example,
filename = 'E:\MASTER\Biofluid mechanics\WIA-Matlab-Biofluid\data2.txt';
myData = importdata(filename); % <---- or readmatrix instead
x=[0:0.005:.625];
myData = [myData ; x']; % <--- assumes same number of rows in x and myData
writematrix(myData, filename);
If your version of MATLAB doesn't support writematrix then you may need to use fprintf or something similar.

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by