Ask an expert. Trust the answer.

Your academic and career questions answered by verified experts

How to MATLAB: Extract multiple parts of a matrix without using loops

Date: 2022-08-03 10:57:55

I have a huge 2D matrix and I would like to extract 15 different 100x100 parts out of it. I have two vectors x and y where the top left indices of the parts are saved. I have used something like this: 

 

 result = cam1(x(1:end):(x(1:end)+99), y(1:end):(y(1:end)+99));

but the result is just a 100x100 matrix instead of a 15x100x100. Why?

I know it could easily be done using a loop but we are not allowed to use loops (it's part of an image processing exercise). Another possbility would be to write all the 15 lines but that is kind of ugly.

Do you have any elegant solution? Thanks. 

 Answers: 

There are a number of ways you could do this without loops. Most solutions involve expanding the vectors x and y into larger matrices of indices and would likely use one or more of the functions REPMAT, BSXFUN, or SUB2IND. A good tutorial for matrix indexing can be found here.

However, since you asked for an elegant solution, here's one that's somewhat unusual. It uses anonymous functions as well as the functions ARRAYFUN and CAT: 

 

indexFcn = @(r,c) cam1(r:(r+99),c:(c+99));
result = arrayfun(indexFcn,x,y,'UniformOutput',false);
result = cat(3,result{:});

EXPLANATION:

The first line creates an anonymous function. This is a simple one line function that can be created on-the-fly without having to put it in an m-file. The function defines two inputs r and c which are used to extract a 100-by-100 submatrix from cam1. The variable indexFcn stores a function handle which is used to call the function. Note that the values of cam1 used by the anonymous function are static. Even if the values in the variable cam1 change, the anonymous function still uses the values that were in cam1 when the function was created.

The second line makes a call to ARRAYFUN, which applies a function to every element of an array. ARRAYFUN loops over each entry in x and y, passing the values to indexFcn. The output is stored in result, a 15-element cell array where each cell contains a 100-by-100 matrix.

The third line uses the CAT function to concatenate the 100-by-100 matrices into a 100-by-100-by-15 matrix.


Why Matlabhelpers ?

Our Matlab assignment helpers for online MATLAB assignment help service take utmost care of your assignments by keeping the codes simple yet of high-quality. We offer the most reliable MATLAB solutions to students pursuing their Computer Science course from the Monash University, the University of Sydney, the University of New South Wales, the University of Melbourne; to name a few. Approach us today for best Matlab solutions online!

whatsApp order on matlabhelpers.com

telegram order on matlabsolutions.com