Sum of Rows
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
I have the below sample of txt file:
Stock Date Time Price Volume Stock Category Trade
ETE 04/01/2010 10145959 18.31 500 Big Cap 1
ETE 04/01/2010 10150000 18.01 70 Big Cap 0
ABC 04/01/2010 10190000 18.34 200 Big Cap 1
YYY 04/01/2010 10200000 18.34 100 Big Cap 1
ETE 04/01/2010 10170000 18.54 430 Big Cap 1
How can I calculate the sum of the seventh column (trade) only for rows with value 'ETE' in column one?
Many thanks in advance
Panos
0 Commenti
Risposta accettata
Matt Fig
il 2 Mag 2011
I simply copied and pasted your data into a textfile I named stock_prices.txt, then:
% Retrieve the data...
fid = fopen('stock_prices.txt');
T = textscan(fid,'%s %10s %n %n %n %s %s %n','headerlines',1);
fclose(fid);
% Now that we have the data, do our math...
idx = cellfun(@(x) isequal(x,'ETE'),T{1});
S = sum(T{end}(idx)) % Sum last column, only rows in idx...
S =
2
7 Commenti
Matt Fig
il 4 Mag 2011
Here is how to do it, given how you are reading the data:
fid = fopen('stock_prices.txt');
% T = textscan(fid,'%s %10s %n %n %n %s %s %n','headerlines',1);
T = textscan(fid,'%s%s%s%s%s%[^\n]','headerlines',1);
fclose(fid);
% Now that we have the data, do our math...
idx = cellfun(@(x) isequal(x,'ETE'),T{1});
valx = str2num(cellfun(@(x) x(end),T{end}));
S = sum(valx(idx)) % Sum last column, only rows in idx...
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Language Support in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!