CroatiaHR
CroatiaHR

Reputation: 625

Matlab sum function from index to index

I am looking for a better way to calculate the sum off all elements from index X to index Y, if I have a list of indexes.
For example:

a = {1, 40, 77} % indexes
cell_elements = {1,1,1.....,1} %100 elements, each 1

My current idea looks something like this:

        counter = 1;
        for k=1:length(cell_elements)
            if(%Some condition) %condition is true for k=1,40 and 77
                sum = sum+cell_elements(k);
                result(counter) = sum;
                sum=0;
                counter = counter+1;      
            else
                sum = sum+cell_elements(k);
            end
        end

I would like to improve the code, since I have the feeling that the problematic is simple, but due to my lack of experience in matlab my code is too long.

Is there any function, where I could just pass a list of indexes and it will do the same job as the code above?

Upvotes: 1

Views: 1710

Answers (1)

Adam
Adam

Reputation: 2777

  • Use array instead of cell
  • Also since your cell_elements are all 1s, you can use the matrix ones(row, column)

Specify the row and the column, here row is 1 and column is 100 this is the code

cell_elements = ones(1, 100)
  • Define a as an array a = [1, 40, 77]
  • First 40 elements are elements having indices from 1 to 40, in Matlab this is equivalent to 1:40, in order to include the array a, since a(1) = 1 and a(2) = 40; set 1:40 as a(1):a(2) First 40 elements will be
First_40_elements = cell_elements(a(1):a(2));

To sum them all together use Matlab built in function sum as follow

Sum_First_40_elements = sum(First_40_elements)
  • For the second 37 elements the indices start from 41 to 77, in Matlab written as 41:77, using array a, a(2)+1:a(3)
    Following the logic above
Second_37_elements = cell_elements(a(2)+1:a(3));

Sum_Second_37_elements = cell_elements(Second_37_elements);

The entire code is as follow

cell_elements = ones(1,100);

a = [1,40,77];

First_40_elements =  cell_elements(a(1):a(2));

Sum_First_40_elements = sum(First_40_elements);
% 40

Second_37_elements =  cell_elements(a(2)+1:a(3));

Sum_Second_37_elements = sum(Second_37_elements);
% 37

The dynamic way is as follow

cell_elements = ones(1,100);
a = [1,25,40, 67, 80, 95];

element_sum = zeros(1, length(a)-1);
for i = 1:length(a)-1
    if i == 1
        element_sum(i) =  sum(cell_elements(a(i):a(i+1)));
    else
        element_sum(i) =  sum(cell_elements(a(i)+1:a(i+1)));
    end
end

Result

>> element_sum

element_sum =

    25    15    27    13    15

>> 

Upvotes: 2

Related Questions