Sum of numbers from a notepad file
2 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
回答 (2 件)
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)
0 件のコメント
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)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Language Support についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!