How do i get my answer to print into a table format instead of a single line
18 次查看(过去 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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/521687/image.png)
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!
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!