2

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?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Shah Fahd
  • 23
  • 2

1 Answers1

4
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
Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 1
    @ShahFahd I edited your original question because there were many syntax errors and it wouldn't run as is. I also removed a lot of the superfluous code to get to the root of your problem. It wasn't me who wrote you the answer. Adriaan did. – rayryeng Nov 04 '15 at 17:42