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

58 ビュー (過去 30 日間)
Braeden McKeown
Braeden McKeown 2021 年 2 月 16 日
コメント済み: dpb 2021 年 2 月 17 日
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 Center および File ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by