Problem by creating Sub Matrices

1 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2017-8-26
编辑:Stephen23 2017-8-26
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 个评论
Haseeb Hassan
Haseeb Hassan 2017-8-26
Thanks for your answer, please can you put the comments for more understanding as i am new bie in matlab and programming.

请先登录,再进行评论。

更多回答(1 个)

MSP
MSP 2017-8-25
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 个评论
Haseeb Hassan
Haseeb Hassan 2017-8-26
编辑:Haseeb Hassan 2017-8-26
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Computer Vision with Simulink 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by