Write a script that will read z and y data points from a file in the following f
ID: 3673146 • Letter: W
Question
Write a script that will read z and y data points from a file in the following format:
w 0 y 1
w 4.6 y 2.2
w 6.8 y 6
w 8.1 y 7.4 The format of every line in the file is the letter ‘w’, a space, the w value, space, the letter ‘y’, space, and the y value. First, create the data file with 10 lines in this format. Save As wypts.dat. The script will attempt to open the data file and error- check to make sure it was opened. If so, it uses a for loop and fgetl to read each line as a string. In the loop, it creates w and y vectors for the data points. After the loop, it plots these points, w vs. z, and attempts to close the file. The script should print whether or not the file was successfully closed.
I understand how to do everything but actually create and then save the data file as wypts.dat. Specifically the creation of the matrix. Will you create the matrix and then save it and show me how to? The problem comes from having strings and integers in the same matrix.
Explanation / Answer
Can help you with this:
id = fopen('zypoints.dat');
if fid == -1
disp('File open not successful')
else
%Initialize z vector and y vector
wvec = 1:10;
yvec = 1:10;
for i = 1:10
aline = fgetl(fid);
%Separate each line into two parts:
w and y [z rest] = strtok(aline,'y');
w(1:2) = [];
[let y] = strtok(rest);
wvec(i) = str2num(w);
yvec(i) = str2num(y);
end
plot(wvec,yvec,'ko')
xlabel('w') ylabel('y')
title('Points from file "wypoints.dat"')
closeresult = fclose(fid);
if closeresult == 0 disp('File close successful')
else
disp('File close not successful')
end
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.