Azzera filtri
Azzera filtri

Sum of numbers from a notepad file

9 visualizzazioni (ultimi 30 giorni)
Vinny
Vinny il 17 Apr 2016
Risposto: Jos (10584) il 18 Apr 2016
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?

Risposte (2)

Jos (10584)
Jos (10584) il 18 Apr 2016
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 il 17 Apr 2016
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)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by