reduce the dimensions of a matrix by averaging a range of columns with the range getting progressively larger. in matlab

Here's an approach you could use to reduce the dimensions of a matrix in MATLAB by averaging a range of columns, with the range of columns getting progressively larger:

  1. Define your input matrix A.
  2. Determine the desired number of output columns, n_out.
  3. For every value n from 1 to n_out, compute the mean of n contiguous columns in A.
  4. Store these means in a new matrix B, with each mean occupying a column of B.
  5. Return B.

Here's what the MATLAB code for this approach might look like:

main.m
% define input matrix and desired number of output columns
A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15];
n_out = 3;

% preallocate output matrix
B = zeros(size(A, 1), n_out);

% loop over range of column numbers to average
for n = 1:n_out
    % compute mean of n contiguous columns in A
    col_idxs = ((n-1)*size(A, 2)/n_out + 1):(n*size(A, 2)/n_out);
    B(:,n) = mean(A(:, col_idxs), 2);
end
394 chars
14 lines

This code assumes that the number of columns in A is evenly divisible by n_out. If not, you'll need to adjust the calculation of col_idxs accordingly to ensure you're averaging the same number of columns in each step of the loop. Additionally, you may want to add error-checking code to ensure that n_out is less than or equal to the number of columns in A.

gistlibby LogSnag