Problem by creating Sub Matrices

1 vue (au cours des 30 derniers jours)
Haseeb Hassan
Haseeb Hassan le 25 Août 2017
Modifié(e) : Stephen23 le 26 Août 2017
I have 5x5 matrix.I want to create 6 submatrices of order 3x3.Uploaded the pic please any one can do it.Or any other methods to do this operation.Thanks

Réponse acceptée

Stephen23
Stephen23 le 26 Août 2017
Modifié(e) : Stephen23 le 26 Août 2017
The more that you set up before the loop, the neater and clearer the code will be:
mat = reshape(1:25,5,5).'; % input matrix, any size
%
blkR = 3; % output block rows
blkC = 3; % output block columns
stpR = 2; % step size rows
stpC = 1; % step size columns
%
inSz = size(mat);
vecR = blkR:stpR:inSz(1); % blocks' end rows
vecC = blkC:stpC:inSz(2); % blocks' end columns
%
numR = numel(vecR); % count blocks along rows
numC = numel(vecC); % count blocks along columns
out = cell(numR,numC);
for kR = 1:numR
for kC = 1:numC
idxR = vecR(kR)+(1:blkR)-blkR; % row indices
idxC = vecC(kC)+(1:blkC)-blkC; % column indices
out{kR,kC} = mat(idxR,idxC); % use indices
end
end
and checking the output:
>> out{:}
ans =
1 2 3
6 7 8
11 12 13
ans =
11 12 13
16 17 18
21 22 23
ans =
2 3 4
7 8 9
12 13 14
ans =
12 13 14
17 18 19
22 23 24
ans =
3 4 5
8 9 10
13 14 15
ans =
13 14 15
18 19 20
23 24 25
>>
  1 commentaire
Haseeb Hassan
Haseeb Hassan le 26 Août 2017
Thanks for your answer, please can you put the comments for more understanding as i am new bie in matlab and programming.

Connectez-vous pour commenter.

Plus de réponses (1)

MSP
MSP le 25 Août 2017
clear all
a=magic(5)
shiftr=2
shiftc=1
k=1
rowsize=3
colsize=3
for i=1:shiftr:size(a,1)
if i+rowsize-1>size(a,1) %%check whether b matrix indices is within a If not then break-i loop
break
end
for j=1:shiftc:size(a,2)
if (j+colsize-1)>size(a,2)
break
else
b(:,:,k)=a(i:i+rowsize-1,j:j+colsize-1)
k=k+1;
end
end
j=1;
end
This is the most basic format of doing it.Have a look and ask if u don't understand.
  1 commentaire
Haseeb Hassan
Haseeb Hassan le 26 Août 2017
Modifié(e) : Haseeb Hassan le 26 Août 2017
Thanks mate, the program working properly, but i am new to this plateform please help to understand me more clearly if you dont mind.I have problem to understand the logic of for loop. Please expalin more with clear information thanks

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by