Sum of numbers from a notepad file

9 次查看(过去 30 天)
Vinny
Vinny 2016-4-17
I have a notepad file with these numbers
1 2 3 4 5 6 7 8 12
8 7 6 5 4 3 2 1 14
I need to take the sum of all the numbers in the 1st row and the sum of all the numbers in the second row and then multiply both sums. I'm having trouble just trying to find the sum first, I copied this code out of my book
filename='C:\Users\Vinny\Documents\exercise1.txt'
fh=fopen(filename,'r');
a=' ';
i=1;
while ischar(a)==true
a=fgets(fh);
if ischar(a)==true
b=sscanf(a,'%f');
rowsum(i)=b(1)+b(2);
i=i+1;
end
end
rowsum
but it gives me
rowsum =
3 15
These are not the summations for both rows. What am I doing wrong?

回答(2 个)

Jos (10584)
Jos (10584) 2016-4-18
If the text file only contains numbers,and there are the same amount on each row, try using load to read the file in matlab:
A = load('numbers.txt')
B = sum(A,2)

Walter Roberson
Walter Roberson 2016-4-17
sscanf() keeps applying the format to the string until that fails, either because of end of string or because of mismatch; sscanf() then returns all the values. You are only adding the first two of those values.
Hint: sum(b)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by