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?

1 Answer 1

5
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
Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.