Convolution Mask
5 views (last 30 days)
Show older comments
To start, I have 3 matrices:
m1= [3 x 3]
m2= [5 x 5]
m2= [7 x7]
I have three loops that are used depending on the size of the matrix. I want to use an "if" command to decifer the size of matrix so the appropriate loop is used.
Here is an example of the 3 x 3 case.
function [matrix]= three_by_three(x,y,I)
if m1 =
matrix= [I(x-1, y-1), I(x-1, y), I(x-1, y+1); I(x, y-1), I(x,y), I(x, y+1); I(x+1, y-1), I(x+1, y), I(x+1, y+1)];
end
0 Comments
Accepted Answer
David Young
on 19 Sep 2011
Something like this?
sz = size(matrix);
if isequal(sz, [3 3])
% first for loop, function call or whatever
elseif isequal(sz, [5 5])
% second
elseif isequal(sz, [7 7])
% third
else
error('myfunction:badsize', 'Unexpected matrix size');
end
You could also use a switch statement.
0 Comments
More Answers (1)
Image Analyst
on 28 Sep 2011
No need to have multiple functions to do this. A single line of code will extract any size submatrix you want. It all comes down to a basic MATLAB instruction like
subMatrix = fullSizeMatrix(row1:row2, col1:col2);
Here's a full demo:
% Generate sample data.
matrix = floor(6*rand(15))+1
[rows columns] = size(matrix)
% Define center of submatrix to extract.
row = 4;
column = 6
% First example: Extract a 3x3 chunk.
sizeToExtract = 3;
halfWidth = floor(sizeToExtract / 2)
subMatrix = matrix(row-halfWidth:row+halfWidth, column-halfWidth:column+halfWidth)
%Second example: Extract a 5x5 chunk.
sizeToExtract = 5;
halfWidth = floor(sizeToExtract / 2)
subMatrix = matrix(row-halfWidth:row+halfWidth, column-halfWidth:column+halfWidth)
By the way, you do know that there is a function called conv2() that does convolution so you don't need to reinvent it, don't you?
See Also
Categories
Find more on Digital Filtering 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!