How to clump/consolidate values together using the mean function

조회 수: 3 (최근 30일)
William Gray
William Gray 2021년 1월 15일
댓글: Alan Stevens 2021년 1월 18일
Hi everyone,
So to explain the title a little more, say I have a 8x8 matrix all of different values, how would I make another 8x8 matrix but just with 4 values in each quadrant?
I have written the following code in an attempt to do this
cw = 4; %cell width
a = [1:8];
b=[1:8]';
c=a.*b;
lp = [1 5]; %length position
mat=ones(8,8); %temporary matrix
for i = 1:numel(lp)
for j = 1:numel(lp)
mat(lp(i):lp(i)+cw-1,lp(i):lp(i)+cw-1)=mean(c(lp(i):lp(i)+cw-1,lp(i):lp(i)+cw-1),"all");
end
end
it partially achieves the desired outcome, calcualting the upper left quadrant as 6.25 and the lower right value as 42.25 but you can see the other quadrants remain as the pre-defined 1.
I'm sure there is an easier way to do this, I probably just don't know the name for what I'm trying to do, but any help would be really appreciated.
Thank you all

답변 (1개)

Alan Stevens
Alan Stevens 2021년 1월 15일
편집: Alan Stevens 2021년 1월 15일
Here's one way
cw = 4; %cell width
a = 1:8;
b = (1:8)';
c = a.*b;
mat=ones(8,8); %temporary matrix
avfn = @(m) mean(m,'ALL');
p = 1:cw; q = cw+1:2*cw;
mat(p,p) = avfn(c(p,p));
mat(p,q) = avfn(c(p,q));
mat(q,p) = avfn(c(q,p));
mat(q,q) = avfn(c(q,q));
  댓글 수: 2
William Gray
William Gray 2021년 1월 18일
Hi Alan
Thank you for the answer, this works great for 4 quadrants. However, say the grid was bigger, 16x16 for example, and so you wanted 16 values instead of 4, is there a more systematic way to calculate this? posibly using a for loop or something of that nature?
Alan Stevens
Alan Stevens 2021년 1월 18일
I think the following does it, though you should check it carefully:
n = 16; % n x n matrix
cw = 4; %cell width
a = 1:n;
b = (1:n)';
c = a.*b;
nc = n/cw; % nc x nc cells (Assumes nc is integer)
mat=ones(n); %temporary matrix
avfn = @(m) mean(m,'ALL');
s = 1;
for i = 1:nc
f = s-1+cw;
p(i,:) = s:f;
s = f+1;
end
for i = 1:nc
for j = 1:nc
mat(p(i,:),p(j,:)) = avfn(c(p(i,:),p(j,:)));
end
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by