How to replace for-loop with matrix multiplication?

I'm trying to replace for-loop with matrix multiplication in order for efficiency. In my case, the matrix is 3-dimensional. I'm not sure how to achieve it. I've attached my code. Could someone help optimize my code?

2 Comments

why reinvent the wheel and not using MATLAB interpolation functions?
This is an assignment to practice the implementation of bilinear interpolation, so I cannot use any relevant function like imresize().

Sign in to comment.

Answers (1)

Hi Duen,
I understand that you are trying to replace the for loops in the given code with matrix multiplication for imroved time efficiency. I assume that the matrix that you are referring to in the question is a different 3 dimensional matrix, since resizedImage is a 2 dimensional matrix.
Here are few steps that I followed to optimize the code:
  1. vectorize variables a and b
  2. generate the weights as a vector
  3. Use element-wise operations for the matrix elements and reshape the matrix to get the desired image size
Please note that the optimized code below assumes that the img matrix contains grayscale pixel values. If you're working with RGB images, you'll need to modify the code accordingly.
function resizedImage = resizeImage_bilinear_Opt(originalImage, scalingFactor)
% load image
img = imread(originalImage);
% get source row and column
[sr, sc] = size(img);
% get destination row and column
dr = ceil(sr * scalingFactor);
dc = ceil(sc * scalingFactor);
% generate row and column indices for the destination image
a = (1:dr) * ((sr - 1) / (dr - 1));
b = (1:dc) * ((sc - 1) / (dc - 1));
% compute the floor and ceil values for row and column indices
x = floor(a);
y = floor(b);
x1 = min(x + 1, sr);
y1 = min(y + 1, sc);
% compute the weights for bilinear interpolation
wa = a - x;
wb = b - y;
wa1 = 1 - wa;
wb1 = 1 - wb;
% perform bilinear interpolation using matrix multiplication
resizedImage = uint8(wa1 .* wb1 .* double(img(x, y)) + ...
wa1 .* wb .* double(img(x, y1)) + ...
wa .* wb1 .* double(img(x1, y)) + ...
wa .* wb .* double(img(x1, y1)));
% reshape the image to the desired size
resizedImage = reshape(resizedImage, dr, dc);
end
Hope this helps.
Regards,
Nipun

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Asked:

on 25 Sep 2023

Answered:

on 5 Oct 2023

Community Treasure Hunt

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

Start Hunting!