Reading full column at a time from a text file
Show older comments
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
on 28 Jan 2018
You appear to have either one or two lines of headers, with the second header value somehow being involved in reading the file. Could you show the actual format? Can different files have different numbers of columns?
Faisal Alnahhas
on 28 Jan 2018
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
on 28 Jan 2018
Accepted Answer
More Answers (0)
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!