Select range based on contents of an array

I have two arrays. I'd like to copy ranges of data from one of them, based on a list of array locations stored in the other. For example, if the first array were comprised of 100 rows and 2 columns, I might like to copy rows 10-20, rows 60-70 and rows 75-79. If that were the case, then the contents of the second array would be as follows:

b =

    10    20
    60    70
    75    79

In order to select the appropriate rows of the first array based on the second (let's call it 'a'), I would do the following:

b = [a(1,1):a(1,2) a(2,1):a(2,2) a(3,1):a(3,2)]

This works, and returns array 'b' which is basically array 'a' with the correct contents extracted.

The problem is, array 'b' actually contains between 50 and 60 rows (i.e ranges to be included).

How do I make the above code more efficient, such that it works for any number of rows in 'b'?

Answers


Example:

a = rand(100,1);
ranges = [
    10    20
    60    70
    75    79
];
idx = arrayfun(@colon, ranges(:,1), ranges(:,2), 'Uniform',false);
idx = [idx{:}];

b = a(idx)

You could use a for, assuming ranges of values to be extracted from a are in b, and should go to c:

% input
a = rand(100,2);
b = [10 20; 60 70; 75 79];
% output
c = zeros(1,2);
for i = 1:size(b,1)
    c = vertcat(c a(b(i,1):b(i,2), :));
end        
c = c(2:size(c,1), :);

A solution using cellfun and cell arrays:

% Some example data:

a = reshape(1:100, 10, 10);
b = [ 2 3; 5 8; 10 10 ];

Here's the code:

bCell = mat2cell(b, 3, [ 1 1 ]);

aRows = cell2mat(arrayfun(@(x,y) a(x:y, :), bCell{1}, bCell{2}, 'UniformOutput', false));

Need Your Help

Two Spring MVC / Maven modules in one project

java spring maven spring-mvc

I try to make a JavaEE application with 2 and more Spring MVC modules. Before I had WebSuite module, that have Web and DB modules

How to create a jks with .key file

java certificate ws-security digital-certificate

I have a .key file created from another team and they have generated .csr from