This problem asks you to read in a text file, perform loops (for loop, do loop,
ID: 3584283 • Letter: T
Question
This problem asks you to read in a text file, perform loops (for loop, do loop, while loop, etc.), apply a conditional statement, and write out a text file. I do not care what language you program the question. Simply that you know how to read/write to a file, how to perform loops and conditional functions within a program. The file hw1_13.txt contains three pieces of information. On line 1: a text description of the file contents On line 2: an integer N, indicating how many (x,y) pairs are in the file. On lines 3:N+2 x and y coordinates. (I've reproduced the file here.) This is a test file containing N coordinate pairs 12 .914149E-02 .583008E-02 .864924E-02 .564676E-02 .758640E-02 .451963E-02 .998525E-02 .694556E-02 .110586E-01.758841E-02 .920563E-02 .593483E-02 .758758E-02 .455107E-02 .963076E-02 .717156E-02 .778348E-02 .530567E-02 .725136E-02 .441892E-02 .642353E-02 .362762E-02 .614649E-02 .342402E-02 Write a program to: Open the file and reads its content, Calculate the vector length for all N pairs of coordinates, [ex: V(i) = sqrt(x(i)^2+y(i)^2) ] Calculate the average vector length, Create an output text file for all coordinate pairs with vector lengths greater than the average vector length, Write to that file the following information: Original input number of the pair and the pair's vector length. My code produced the following: 0.010842 0.010329 0.012163 0.013412 0.010953 0.012008 (note that coordinate pairs 3,7,9,10,11 and 12 must have had a vector length less than the average vector length. Therefore, their information was not written to the output file)Explanation / Answer
[fid,msg]=fopen('hw1_13.txt', 'r'); if (strcmpi(msg,'') ==0) fprintf('File ''hw1_13.txt'' fail to open '); else fprintf('File ''hw1_13.txt'' opened successfully '); N=fscanf(fid,'%i'); for i=1:N tline=fgetl(fid); a=textscan(tline,'%f %f'); x(i)=a{1}; y(i)=a{2}; V(i)=sqrt(x(i)^2 +y(i)^2); end avgV=mean(V);% get average [fid2,mgs]=fopen('outputfile.dat','w'); if (strcmpi(msg,'') ==0) fprintf('File ''outputfile.dat'' fail to open '); else fprintf('File ''outputfile.dat'' opened successfully '); for i=1:N if(V(i)>=avgV)% if equal or higher, print to fid2 fprintf(fid2,'%d %f ',i,V(i)); end end %close file close=fclose(fid);%0 success, -1 failed if(close~=0) fprintf('File ''hw1_13.txt'' close failed '); else fprintf('File ''hw1_13.txt'' closed successfully '); end close=fclose(fid2); if(close~=0) fprintf('File ''outputfile.dat'' close failed '); else fprintf('File ''outputfile.dat'' closed successfully '); end end end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.