MATLAB: Extraction of subrows of different length

different sizeextractionindexing

Hi,
I have a matrix of boolean n*m say:
A =[0 1 1 1 0; 0 1 1 0 1; 0 1 0 1 1; 0 0 1 0 1]
I have 2 vectors of size n of starting and ending indexes corresponding to the columns of A, say:
iStart = [2 2 4 5];
iEnd = [4 5 5 4];
I would like to check whether, for each row of A, all the booleans for the columns in between iStart and iEnd are true. The loop version would be:
bool = false(size(A,1))
for i = 1:size(A,1)
if cumprod( A(i, iStart(i):iEnd(i)) )
bool(i) = true;
end
end
In the above example, we would have:
bool = [1 0 1 0]
So I was wondering whether there is a smarter kind of vectorized version of this that would speed up the code ? I am usually not bad for vectorizing stuff but the different sizes are not very nice for Matlab and give me troubles.
Thanks a lot 🙂

Best Answer

One solution
>> arrayfun(@(i1,i2,i) all(A(i,i1:i2)),iStart,iEnd,[1:size(A,1)])
ans =
1×4 logical array
1 0 1 1
>>
altho your loop may be just as fast or faster...
for i=1:size(A,1)
B(i)=all(A(i,iStart(i):iEnd(i)));
end