Shah Fahd
Shah Fahd

Reputation: 23

Adding multiple rows in Array

I have an array A size of 16X16 and I want to add first 3 rows out of 16 in A. What is the most efficient solution in MATLAB?

I tried this code but this is not efficient because I want to extend it for large arrays:

filename = 'n1.txt';
B = importdata(filename);
i = 1;
D = B(i,:)+ B(i+1,:)+ B(i+2,:);

For example, if I want to extend this for an array of size 256x256 and I want to extract 100 rows and add them, how I will do this?

Upvotes: 2

Views: 288

Answers (1)

Adriaan
Adriaan

Reputation: 18177

A(1:3,:);%// first three rows.

This uses the standard indices of matrix notation. Check Luis's answer I linked for the full explanation on indices in all forms. For summing things:

B = A(1:100,:);%// first 100 rows
C = sum(B,1);%// sum per column
D = sum(B,2);%// sum per row
E = sum(B(:));%// sum all elements, rows and columns, to a single scalar

Upvotes: 4

Related Questions