Sum along absolute values in an Array in Matlab

2.4k Views Asked by At

My array contains a string in the first row

how can I sum the array from the 2nd row to the Nth/1442th row (as in my example) disregarding the negative signs present in the column?

for example, my code for an array called data2 is:

S = sum(data2(2,15):data2(1442,15));

so sum all of the elements from row 2 to row 1442 in column 15. This doesn't work but it also does not have anything to deal with the absolute value of whatever row its checking

data is from a .csv:enter image description here

2

There are 2 best solutions below

3
On BEST ANSWER

You should do something like this:

sum(abs(data(2:1442,15)));

The abs function will find the absolute value of each value in the array (i.e. disregard the negative sign). data(2:1442,15) will grab rows 2-1442 of the 15th column, as you wanted.

EDIT: apparently data is a cell array, so you could do the following, I think:

sum(abs([data{2:1442,15}]));
0
On

Ok so it looks like you have a constant column so

data2(2,15) = -0.02

and further down

data2(1442,15) = -0.02 %(I would assume)

So when you form:

data2(2,15):data2(1442,15)

this is essential like trying to create an array but of a single value since:

-0.02:-0.02

ans =

   -0.0200

which of course gives:

>> sum(-0.02:-0.02)

ans =

   -0.0200

What you want should be more like:

sum(data2(2:1442,15))

That way, the index: 2:1442, forms a vector of all the row references for you.

To disregard the negative values:

your answer = sum(abs(data2(2:1442,15)))

EDIT: For a cell array this works:

sum(abs(cell2mat(data2(2:1442,15))))