rth
rth

Reputation: 3106

average using index form the array

I have and time sequence: lines are channels, columns are time points, say

x = [1 2 3 4 5 6 7 8; 9 10 11 12 13 14 15 16; 17 18 19 20 21 22 23 24 ; 25 26 27 28 29 30 31 32]
x =

    1    2    3    4    5    6    7    8
    9   10   11   12   13   14   15   16
   17   18   19   20   21   22   23   24
   25   26   27   28   29   30   31   32

I have an index of a specific points in time when I want to compute mean for the x

y = [4 5 6]
y =
   4   5   6

How can I get a 3D array out of x with +- 2 points around and average thrue 3d dimation? In over words, I need to average

 3  4  5           4  5  6       5  6  7
11 12 13   and    12 13 14 and  13 14 15
19 20 21          20 21 22      21 22 23
27 28 29          28 29 39      29 30 31

for each entrance.

Upvotes: 0

Views: 65

Answers (2)

Marco Torres
Marco Torres

Reputation: 186

Since the mean is of all the rows, just get the 3 chunks (1 before, the index, and 1 after) and calculate the mean value. I didn't use the mean function since will calculate the mean of each column. Instead of that, I just add the 3 chunks and divide them by 3.

% Get the x values
x = [1 2 3 4 5 6 7 8;...
    9 10 11 12 13 14 15 16;...
    17 18 19 20 21 22 23 24 ;...
    25 26 27 28 29 30 31 32]
% Define the idx
idx = [4 5 6]
% Get the mean matrix. It is the mean of 1 column before
%  the idx and 1 column after. Since there are 3, divided by 3.
%              1 before    index     1 after
MeanMatrix = (x(:,idx-1)+x(:,idx)+x(:,idx+1))./3

Upvotes: 1

Josh
Josh

Reputation: 328

The best approach i think would be to loop over the array something like this:

result = [];

for i = 1:length(y)
    result = [result, mean(x(1:height(x),y(i)-1:y(i)+1), 'all')];
end

Here, we are just splitting it into the chunks you want using indexing then computing the mean over the entire selected chunk.

Upvotes: 0

Related Questions