Cameron - 2022-06-17T12:33:25+00:00
Question: Extracting numerical data from text file
#Terrain File Terrain.mat #Start Point (xs,ys) -4.8 4.0 From the code above I am trying to extract "-4.8" and save it as xs, and "4.0" saved as ys. I don't know how to tell matlab to look for the "#" that will be at the beginning of every category. this is the project text file code please convert to project.text file for solving. #This is a project file for MAE8 Spring 2014 #Terrain File Terrain.mat #Start Point (xs,ys) -4.8 4.0 #End Point (xe,ye) 4.8 -4.8 #Number of Way Points 2 #Way Points (xwp,ywp) -0.5 4.8 4.7 0.8
Expert Answer
Prashant Kumar answered .
2025-11-20
If all you need is that start point coordinates, then about the simplest is just
>> [xs ys]=textread('project.txt','%f %f', 1, ...
'headerlines',4,'commentstyle','shell');
>> disp([xs ys])
-4.8000 4.0000
If, otoh, you need the other info as well, then it's essentially the same presuming you'll do a little post-processing--
>> [xs ys]=textread('project.txt','%f %f', ...
'headerlines',4,'commentstyle','shell');
>> disp([xs ys])
-4.8000 4.0000
4.8000 -4.8000
2.0000 0
-0.5000 4.8000
4.7000 0.8000
>>
The only difference in the textread is the removal of the count of 1 to limit the first past to the one record; it instead iterates over the entire file from the 7th line on.
Note the #waypoints record is returned as [2 0]; hence one can use
ix=find(ys(:,2)==0};
as the locator for that record; get the number from the first column and then process the remaining records as the actual points.
ADDENDUM Actually, it dawned on me you don't need to search for the number of waypoints; it'll always (at least appears will be from this example file) the third row, so
np=xs(3);
*END*
You can get more complicated w/ textscan and/or scan thru on a record basis to find the sections, but sometimes the older, simpler ways are, well, just simpler...
Now, if you change your mind and also want the text line of the .mat file name, then textread isn't your friend as can't mix metaphors therein (so to speak, it can't mix the string/character data and the numeric). Then your options revert to textscan or the old standby fgetl. It doesn't look like these would ever be very large files so reading and processing the header and section heading lines on a record-by-record basis wouldn't be bad from a performance standpoint. Once you get to the waypoints section you can read the array w/ fscanf directly. This way has the advantage that you can make variable names for the sectional variables rather than using the row indices, but it's pretty much immaterial as to how from a practical standpoint.
Not satisfied with the answer ?? ASK NOW