Using reshape to manipulate a large matrix
2 views (last 30 days)
Show older comments
Patrick O'Mahony
on 24 Apr 2020
Edited: per isakson
on 25 Apr 2020
I have a 10000x10000 matrix of data that I'm trying to scale down. You goal is to make it a 400x400 matrix by taking every cell in 25x25 cell chunk and averaging them into one value. I'm trying to use the reshape function to do this, but I dont know how to scale down the matrix by any factor other than 2, the code for that is below. Any advice on hw I can do to adapt or rewrite this is appreciated.
[x,y] = size(matrix);
x1 = x/2;
y1 = y/2;
R = reshape(reSizedData,2 , x1, 2, y1);
S = sum(sum(R, 1), 3) * 0.5;
Y = reshape(S, x1, y1);
0 Comments
Accepted Answer
per isakson
on 25 Apr 2020
Edited: per isakson
on 25 Apr 2020
"I dont know how to scale down the matrix by any factor other than 2" What's wrong with your code?
I think your code works just fine with scale down by 25
%%
M = 1:1:1e8;
M = reshape( M, 1e4, 1e4 );
%%
tic
[x,y] = size( M );
x1 = x/25;
y1 = y/25;
R = reshape( M, 25, x1, 25, y1 );
S = sum( sum(R,1), 3 );
Y1 = reshape( S, x1, y1 );
toc
%%
Y2 = nan( 4e2, 4e2 );
tic
for rr = 1 : 1 : 4e2
for cc = 1 : 1 : 4e2
chunk = M( (rr-1)*25+1:rr*25, (cc-1)*25+1:cc*25 );
Y2(rr,cc) = sum(chunk(:));
end
end
toc
%%
imagesc(M)
figure
imagesc(Y1)
figure
imagesc(Y2)
Your result and the for-loop result are identical!
>> all(all(Y1==Y2))
ans =
logical
1
>>
And I think your code works just fine with "any" scale down factor
%%
M = 1:1:1e8;
M = reshape( M, 1e4, 1e4 );
D = 2e2; % 1e4/D must be a whole number
%%
tic
[x,y] = size( M );
x1 = x/D;
y1 = y/D;
R = reshape( M, D, x1, D, y1 );
S = sum( sum(R,1), 3 );
Y1 = reshape( S, x1, y1 );
toc
%%
M = 1:1:1e8;
M = reshape( M, 1e4, 1e4 );
Y2 = nan( 1e4/D, 1e4/D );
tic
for rr = 1 : 1 : 1e4/D
for cc = 1 : 1 : 1e4/D
chunk = M( (rr-1)*D+1:rr*D, (cc-1)*D+1:cc*D );
Y2(rr,cc) = sum(chunk(:));
end
end
toc
%%
imagesc(M)
figure
imagesc(Y1)
figure
imagesc(Y2)
%%
all(all(Y1==Y2))
Or what have I missed?
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!