MATLAB: Reading full column at a time from a text file

columns from text fileiterating over cell arrays

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);

Best Answer

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.