MATLAB: Help improving the speed of find

findMATLABperformancespeed

Please have a look at the below code which is a minimum working example of my actual implementation. The thing I'm wondering about is inside the CODE OF INTEREST block. Basically, I have a matrix A of size MxNxO and a vector x of size O. For each vector in matrix A at position A(i,j,:) of size O, I want to compare it to vector x, and find the first indices where x is smaller than A(i,j,:). As you see in the code below I'm using two for loops together with a reshape in order to make this work, but I'm curious if there is a faster way to achieve this? I've been trying something along the lines of: find(x < A(:,j,:), 1, 'first') but I have not been able to make this work. I can also add that the vectors in A(i,j,:) is sorted and always have a larger range than x – x is not sorted.
clc
close all
clear
%--- SETUP ---%
A = zeros([5,5,5]);
for i=1:size(A,1)
for j=1:size(A,2)
A(i,j,:) = linspace(-0.5,1,size(A,3));
end
end
x = rand(1,size(A,1));
B = zeros(size(A,1), size(A,2));
%--------------%
%--- CODE OF INTEREST ---%
for i=1:size(A,1)
for j=1:size(A,2)
B(i,j) = find(x(i) < reshape(A(i,j,:),[size(A,3),1]), 1, 'first');
end
end
%------------------------%
%--- PRINT OUTS ---%
for i=1:size(A,1)
for j=1:size(A,2)
reshape(A(i,j,:),[size(A,3),1])
end
end
x
B
%------------------%
EDIT
Thanks for all the replies so far. I feel like I have to point out that the stuff inside the SETUP block is not really relevant, in the real application this stuff is generated elsewhere, this was just to make a minimum working example. The code inside the CODE OF INTEREST block is exactly as in my application and is the part I'm curious about whether there exists a more efficient way to solve, given the format of A,B and x as specified above.

Best Answer

Loops, loops, loops... so many loops!
Better to vectorize your code:
B = 1+sum(bsxfun(@ge,x(:),A),3)