Borrar filtros
Borrar filtros

How do i get my answer to print into a table format instead of a single line

26 visualizaciones (últimos 30 días)
Hello,
I am trying to code to have data taken from a file and then transcribed into a new one. The process is working fine except i cannot get the code to print onto the new file in a table format that looks like the top one
The file im given the values from looks like
20 200
30 250
25 300
20 400
My code looks like this
data=load('Lab3Problem2.txt');
%set matrix for newtons
N=data(:,1);
%set matrix for spring constant
k=data(:,2);
%find length using x=N/k
len_N=length(N);
x=zeros(len_N,1);
%create the Length array
for i = 1:len_N
x(i)=N(i)/k(i)
end
E=zeros(len_N,1);
for i=1:len_N
E(i)=(k(i)*x(i).^2)/2;
end
%write the data to answers txt file
fid=fopen('Springsanswers','wt');
fprintf(fid,'Spring1 Spring2 Spring3 Spring4');
fprintf(fid,'Force(N) %10d %10d %10d %10d',N');
fprintf(fid,'Spring Constant(N/m) %10d %10d %10d %10d',k');
fprintf(fid,'Potential energy(J) %10f %10f %10f %10f',E');
fclose(fid);
The solves the questions correctly however it displays the answer like this
Spring1 Spring2 Spring3 Spring4Force(N) 20 30 25 20Spring Constant(N/m) 200 250 300 400Potential energy(J) 1.000000 1.800000 1.041667 0.500000
Which is all in one row and not the way that is being required.
Any help would be appreciated!

Respuesta aceptada

Star Strider
Star Strider el 16 de Feb. de 2021
Your code is close. Use tab characters ('\t') and carriage return-newline ('\n') characters as appropriate:
fprintf(fid,'\t\t\t\t\t\t\tSpring1\t\tSpring2\t\tSpring3\t\tSpring4\n');
fprintf(fid,'Force(N)\t\t\t\t%10d\t%10d\t%10d\t%10d\n',N');
fprintf(fid,'Spring Constant(N/m)\t%10d\t%10d\t%10d\t%10d\n',k');
fprintf(fid,'Potential energy(J)\t\t%10f\t%10f\t%10f\t%10f\n',E');
See the documentation on fprintf completely to understand all the interesting possibilities it has to offer.
  4 comentarios
Steven Lord
Steven Lord el 17 de Feb. de 2021
If you have a table array you want to write to a file, see writetable.
dpb
dpb el 17 de Feb. de 2021
Being homework, I figured writetable was probably off the table... :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by