Skip to content

Instantly share code, notes, and snippets.

@arraytools
Last active March 29, 2020 00:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save arraytools/26a0b359541f4fc9fddc8f0a0c94489e to your computer and use it in GitHub Desktop.
Three program languages to compute the sum of a numerical matrix (with column header)
// C++ program to find the sum of an
// of unknown numbers of rows and columns of a matrix
#include <fstream>
#include <iostream>
#include <string>
#include <sstream> // stringstream
#include <stdlib.h>
using namespace std;
int main()
{
double sum, sum1, value;
ifstream fin("GX_datab31.txt");
if (!fin) {
std::cout << "Cannot open file.\n";
return 0;
}
string item;
sum = 0;
sum1 = 0;
getline(fin, item); // ignore the first row
string line;
int ncol = 0, nrow = 0;
stringstream iss;
while(getline(fin, line)) { // step 2. extract a line ("\n" is the default delimiter) from a (file) stream
nrow++; // accumulate row number.
iss << line; // step 3. insert a string to a stringstream
while (iss >> value) { // step 4. extract a string from a stringstream
if (nrow == 1 ) {
sum1 = sum1 + value;
++ncol;
}
// cout << item << endl;
sum = sum + value;
}
iss.clear(); // step 5. clear the error state of the stream?
}
cout << "There are " << nrow << " rows and " << ncol << " columns\n"; cout << "Done\n";
fin.close();
printf("sum: %20.10f\n", sum);
printf("sum1: %6.15f\n", sum1);
return 0;
}
/*
There are 1579 rows and 463 columns
Done
sum: 12589441.4342235196
sum1: 4787.087759999993978
*/
import numpy as np
# numerical data file
filename="GX_datab31.txt"
data = np.loadtxt(filename, delimiter="\t", skiprows=1)
print (data.shape)
def row_sum(arr) :
sum = 0
sum1 = 0
# finding the row sum
for i in range(data.shape[0]) :
for j in range(data.shape[1]) :
# Add the element
sum += arr[i][j]
if i ==0:
sum1 = sum
# Print the row sum
print("Sum =",sum)
print("Sum1 =", sum1)
if __name__ == "__main__" :
row_sum(data)
'''
(1579, 463)
('Sum =', 12589441.43422352)
('Sum1 =', 4787.087759999994)
'''
x <- read.delim("GX_datab31.txt")
dim(x)
# [1] 1579 463
sum(x)
sum(x[1, ])
options(digits = 20)
sum(x)
# [1] 12589441.434223400429
sum(x[1,])
# [1] 4787.087760000000344
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment