Exporting matrix as .txt file

5 visualizaciones (últimos 30 días)
Paul
Paul el 9 de Ag. de 2020
Respondida: Cris LaPierre el 9 de Ag. de 2020
Hello,
I am trying to export the 189x12 matrix "newMatrix" from the following code as an ASCII .txt file with headers. The export works until the 20th row but the remaining rows are unsorted.
clear all
clc
A1 = importdata('Particles.txt');
A2 = importdata('Fragments.txt');
ID_Particles = A1(:,2);
MID_Fragments = A2(:,6);
CooParticles = A1(:,9:11);
ID_Fragments = A2(:,1);
Duration = A2(:,2);
Coo_Fragments = A2(:,3:5);
Mother_ID = A2(:,6);
Generation = A2(:,7);
x = size(A2,1);
newMatrix=zeros(size(A2,1),12);
newMatrix(:,1)=A2(:,1);
for k=1:length(ID_Particles)
a=MID_Fragments==ID_Particles(k);
newMatrix(a,2:4)=repmat(CooParticles(k,:),nnz(a),1);
end
newMatrix(:,5) = Duration;
newMatrix(:,6:8) = Coo_Fragments;
newMatrix(:,9) = Mother_ID;
newMatrix(:,10) = Generation;
fileID = fopen('Coordinates.txt');
fprintf(fileID,'%8s %10s %10s %10s %10s %10s %10s %10s %10s %10s\r\n' ,'header1','header1','header1','header1','header1','header1','header1','header1','header1','header1');
fprintf(fileID,'%3d\r %4.8e %4.8e %4.8e %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f\r\n',newMatrix);
fclose(fileID);
Does anyone have an idea how to solve this problem?
All required files are attached.

Respuestas (1)

Cris LaPierre
Cris LaPierre el 9 de Ag. de 2020
The best approach would be to define a variable for each format specified in your fprintf statement. Without it, MATLAB, which is column-major ordered by default, will populate the fields marching down the rows of the first column first, then move to the second, etc. Keep in mind that newmatix is 189x12, but you only have 10 fields. You'll need to transpose newMatrix:
fprintf(fileID,'%3d\r %4.8e %4.8e %4.8e %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f\r\n',newMatrix(:,1:10)');
The remaining issues are related to how you have coded the creation of newMatrix. Since I'm not sure what it is you are trying to do, I suggest you take a look at what each line is doing an check that it is what you want.

Categorías

Más información sobre Variables 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