How to read data from a matrix according to the lower and upper index range

1 view (last 30 days)
Given one logical matrix a, b defines the lower and upper index range of each row of a to be 1. May I know how to vectorize the following code, as the loop is huge (1,000,000 loops) for the real case?
a=zeros(5,24,'logical');
b=[2 4;5 7;8 9;1 10;12 15];
for i=1:5
a(i,b(i,1):b(i,2))=1;
end

Accepted Answer

sloppydisk
sloppydisk on 1 May 2018
Define a grid to perform logical indexing on:
n = 24;
m = 5;
gridx = repmat(1:n, m, 1);
b=[2 4;5 7;8 9;1 10;12 15];
a = gridx >= b(:, 1) & gridx <= b(:, 2);
That should do the trick.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!