Ali Koleiny
Ali Koleiny

Reputation: 13

Is there a way to combine columns from multiple text files into a single text file using Matlab?

I'm using Matlab to combine columns from 4 individual text files into a single new text file in Matlab. Each text file has the same number of rows (5478). I found this similar issue here...

Read multiple text files and import each of them as columns

I took Ray's second suggestion from that link, but it still did not work. My code looks like the following...

 textDataMatrix = zeros(5478, 4);
 t = {'prec', 'rsds', 'tmax', 'tmin'};

  for k = 1:4
    Mead_NE_Climate_1985_1999 = [t{k} '_outfile_mead.txt'];
    fid = fopen(Mead_NE_Climate_1985_1999, 'rt');
    textData = fread(fid);
% Place the k'th text data in the k'th column
  textDataMatrix(:,k) = textData;
  fclose(fid);
 end  

For some reason, I get the following error...

Subscripted assignment dimension mismatch.

Error in Mead_Text_Climate (line 10) textDataMatrix(:,k) = textData;

I have visually inspected all of the text files, and they each have the same number of rows/lines. So I'm struggling to understand why this isn't working. Can anyone help? Thanks for your time! First few lines containing daily Precipitation Values

Upvotes: 1

Views: 190

Answers (2)

rayryeng
rayryeng

Reputation: 104464

Try using readmatrix instead. What's nice about this function is that it can handle NaN values, which is what some of your text files have. Also, because your text files have commas, this will confuse the function and think there is a second empty column. Just subset into the first column to be safe. Please note that this function exists in version 2019a or greater:

textDataMatrix = zeros(5478, 4);
t = {'prec', 'rsds', 'tmax', 'tmin'};
for k = 1:4
    Mead_NE_Climate_1985_1999 = [t{k} '_outfile_mead.txt'];
    textData = readmatrix(Mead_NE_Climate_1985_1999);
    textDataMatrix(:,k) = textData(:,1);
end

Upvotes: 1

Emrah Diril
Emrah Diril

Reputation: 1755

fread reads files as binary even though you fopen your files in text mode. The output is a vector of bytes (but stored as doubles). (See matlab doc for fread)

Instead, you want to use a different method to read your file as text, such as fscanf.

Assuming the data in your files is floating point numbers (and have a comma at the end of each row), the following should do what you want:

textDataMatrix = zeros(5478, 4);
t = {'prec', 'rsds', 'tmax', 'tmin'};

for k = 1:4
   Mead_NE_Climate_1985_1999 = [t{k} '_outfile_mead.txt'];
   fid = fopen(Mead_NE_Climate_1985_1999, 'rt');
   textData = fscanf(fid, '%f,');
   textDataMatrix(:,k) = textData;
   fclose(fid);
end

Upvotes: 0

Related Questions