필터 지우기
필터 지우기

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

조회 수: 26 (최근 30일)
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!

채택된 답변

Star Strider
Star Strider 2021년 2월 16일
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
Steven Lord
Steven Lord 2021년 2월 17일
If you have a table array you want to write to a file, see writetable.
dpb
dpb 2021년 2월 17일
Being homework, I figured writetable was probably off the table... :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by