Borrar filtros
Borrar filtros

Sum of numbers from a notepad file

5 visualizaciones (últimos 30 días)
Vinny
Vinny el 17 de Abr. de 2016
Respondida: Jos (10584) el 18 de Abr. de 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?

Respuestas (2)

Jos (10584)
Jos (10584) el 18 de Abr. de 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 el 17 de Abr. de 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)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by