Reading full column at a time from a text file

5 views (last 30 days)
Hi, I am new to Matlab. I have a text file that looks something like this:
1 2 3
4 5 6
7 8 9
I need to add each column separately before I do something with the result. So I need three variables such that
c1 = sum of 1+4+7
c2 = sum of 2+5+8
c3= sum of 3+6+9.
I am reading the text file using using two methods (just trying to see which is better) but they both give me a cell array that reads A = {1, 2, 3, 4, ...}. Here's my code, I appreciate your help.
file_length = 40;
w = [3 -1.5 -2]
entry = [];
fileID = fopen('training_inputs1.txt', 'r');
formatSpec = '%f';
A2 = fscanf(fileID, formatSpec)
A = textscan(fileID, formatSpec);
%r1 = A2(:,1),
for i = A2 %1:file_length
disp(i(:))
%value = sprintf(formatspec, i)
%i2 = i + 1;
%i3 = i + 3;
%Y2 = w(2) * i2
%Y3 = w(3) * i3
end
%Y = Y1 + Y2 + Y3
fclose(fileID);
  4 Comments
Walter Roberson
Walter Roberson on 28 Jan 2018
I missed something in your existing code.
Your A2 = fscanf(fileID, formatSpec) is telling MATLAB to read the entire file as %f format, stopping only when it finds something that cannot be interpreted a floating point number. With your data file, that ends up reading to the end of file. You did not specify a size, so the data will be returned as a column vector.
Then the A = textscan(fileID, formatSpec) tells MATLAB to pick up in the file from where you previously left off and read the rest of the file as floating point numbers, stopping only when it finds something that cannot be interpreted as a floating point number. Because the fscanf already read the entire file, the textscan has nothing to read.
Then your for i = A2 tells MATLAB to iterate with the variable i being set to each column of A2 in turn. A2 only has a single column, so the body of the for loop will be executed once, with i being set to the entire contents of the file...
Faisal Alnahhas
Faisal Alnahhas on 28 Jan 2018
Hi again,
The reason I used both fscanf and textscan is because I was trying to see if one of them has advantage over the other. One of them should be commented, it just so happened that it was not when I posted the code. Anyway, what do you recommend I use then?

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 28 Jan 2018
We do not recommend that you process one column at a time. Read in all of the columns into a 2D array, and use sum() on that 2D array: the result will be a row vector with one total per column. You do not need different variables for each column: just index the vector.
  3 Comments
Faisal Alnahhas
Faisal Alnahhas on 29 Jan 2018
That worked perfectly! Thank you very much. Like I said I'm new to this, today is my 3rd day using Matlab.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!