Jerry
Jerry

Reputation: 107

Getting the average of specific points in a matrix using for loops

I have a matrix called V1all which has 1556480 variables in it. All in the first column. I am trying to get the average over every 1024 points. i.e. the average of the first 1024 points, then the second 1024 points and so on. In the end I should have a matrix with 1520 points. I have the following code but I only get one value repeated 1520 times.

V1 = zeros(1520,1);
for jj = 1024:1024:1556480;
V1(1:1520) = mean(V1all(jj-1023:jj));
end

Any idea what I am doing wrong? Regards, Jer

Upvotes: 1

Views: 45

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You can do it in one line: reshape into a 1024-row matrix and them apply mean to compute the mean of each column:

V1 = mean(reshape(V1all, 1024, []));

If you really want to use a loop: You are not indexing V1 correctly. Modify your code as follows:

V1 = zeros(1520,1);
for n = 1:1520;
    jj = 1024*n;
    V1(n) = mean(V1all(jj-1023:jj));
end

Upvotes: 2

Related Questions