The Math Forum

Search All of the Math Forum:

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

Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]

Posts: 3
Registered: 9/11/13
Re: matrix mean
Posted: Sep 11, 2013 5:13 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

"Puneet" wrote in message <l0kc2v$l2a$>...
> 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)
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(:));

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

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

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

% Method 3
% generalized shift
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);
E = D(1:n:end, :);
for k = 2:n
E = E + D(k:n:end, :);
E = E/n^2;

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.



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2017. All Rights Reserved.