Help with textread please

2 views (last 30 days)
Stephen
Stephen on 13 Oct 2014
Edited: Geoff Hayes on 14 Oct 2014
Hey, I basically need to textread two certain rows out of a text file.
Here's what I've got. I need to extract 2 certain rows from the fileID. No columns. Essentially the text file is a bunch of elevations by year, it's 8 years by 12 months, 2000-2007, I need to take out just 2003 and 2004 in order to print it with printmat. Any help soon would be appreciated. Thanks!
clc clear all
FILENAME = 'lake_powell.txt'; fileID = fopen('lake_powell.txt'); NUM_MONTHS = 12; NUM_YEARS = 8;
for MONTH = 1:NUM_MONTHS for YEAR = 1:NUM_YEARS lake_powell(MONTH,YEAR) = fscanf(fileID, '%f', 1); end end
ELEV = textread(fileID, '?', ?);
printmat(ELEV, 'Lake Powell Water Levels (in feet)', 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec', '2003, 2004');

Answers (1)

Geoff Hayes
Geoff Hayes on 14 Oct 2014
Edited: Geoff Hayes on 14 Oct 2014
Stephen - what is the format of your file? For example, are all rows the same in that they have the same number of columns? If so, what is the format for each row - all numeric, mixture of alphabetic and numeric, etc.?
Part of your code (that which uses fscanf) seems to imply that your data is just a single column of 8*12 elements, one elevation value per month per year. If that is the case, then you could simply use importdata to get the data from file as
elevationData = importdata('lake_powell.txt');
The 2003 data would start at index 12*(4-1)+1 and run through to 12*(5-1), and the 2004 data would start at index 12*(5-1)+1 and run through to 12*(6-1)
elevationData2003 = elevationData(12*3+1:12*4);
elevationData2004 = elevationData(12*4+1:12*5);
The indexing is clear if you think about how each year works: 1-12 for 2000, 13-24 for 2001, 25-36 for 2002, 37-48 for 2003, 49-60 for 2004, etc.
You can then print out the data as
printmat([elevationData2003 elevationData2004], 'Lake Powell Water Levels (in feet)', ...
'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec', '2003 2004');
printmat seems to be a function that doesn't exist with more recent versions of MATLAB. If you have a newer version, then consider using the table functionality.
It may be that your version of MATLAB doesn't support importdata. Is that why you wanted to use textread? Which version of MATLAB do you have?
You should be able to take the same code above and just replace importdata with textread.

Categories

Find more on Dates and Time in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!