Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: matrix mean
Replies: 9   Last Post: Sep 11, 2013 5:13 PM

 Messages: [ Previous | Next ]
 arich82 Posts: 3 Registered: 9/11/13
Re: matrix mean
Posted: Sep 11, 2013 5:13 PM

"Puneet" wrote in message <l0kc2v\$l2a\$1@newscl01ah.mathworks.com>...
> Hi - this is begginers question.
> I have a data set - 16 rows and 16 columns - I would like to average every 2 points to get an 8 rows 8 columns matrix.
>
> This is a learning phase so I can run something similar later for larger data sets.
> Thanks.

I'm assuming this loop does what you want using subarrays:

%%%%%%%%%%%%%
N = 2^4; %N=2^9;
A = reshape(1:N^2, [N, N]); % dummy data

% Method 1
% Simple loop
% (could be further optimized, but probably not best method)
tic;
B = NaN(N/2, N/2);
for j = 1:N/2
j1 = 2*j - 1;
j2 = 2*j;
for i = 1:N/2
i1 = 2*i - 1;
i2 = 2*i;
a = A(i1:i2, j1:j2);
B(i, j) = mean(a(:));
end
end
toc;
%%%%%%%%%%%%%%%%%

B is a coarsened image of A. An alternative (and faster method)

%%%%%%%%%%%%%%%%%
% Method 2
%
tic;
C = A(:, 1:2:end-1) + A(:, 2:2:end);
C = C(1:2:end-1, :) + C(2:2:end, :);
C = C/4;
toc;
%%%%%%%%%%%%%%%%%%%

More generally, for a window size of n-by-n (instead of 2-by-2)

%%%%%%%%%%%%%%%%%%%
% Method 3
% generalized shift
tic;
n = 2; %could set n=4 to coarsen usng 4-by-4 subarray;
D = A(:, 1:n:end); % effectively preallocates loop
for k = 2:n
D = D + A(:, k:n:end);
end
E = D(1:n:end, :);
for k = 2:n
E = E + D(k:n:end, :);
end
E = E/n^2;
toc;
%%%%%%%%%%%%%%%%%%%

There may be more efficient ways, but this one seems to scale pretty well if you're not memory bound; you could get creative and make it more memory efficient, and make it prettier by turning the loop over k into a function and just run it again on D.', but hopefully this addresses the first question.

--Andy

--Andy

Date Subject Author
9/9/13 Puneet
9/9/13 Curious
9/9/13 Curious
9/9/13 dpb
9/10/13 Puneet
9/10/13 Curious
9/10/13 dpb
9/10/13 dpb
9/10/13 Steven Lord
9/11/13 arich82