MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply TodayTo resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

Asked by none on 14 Mar 2013

I have code which does

for t = 1: length(vector2) idx(t) = find(vector <=vector2(t), 1, 'last'); end

Can I call find.m without using a for loop (or bsxfun.m) and if so how?

Or should I just use histc?

[~,idx]=histc(vector2, vector);

*No products are associated with this question.*

Answer by Friedrich on 14 Mar 2013

Edited by Friedrich on 14 Mar 2013

Accepted answer

Hi,

use bsxfun and make sure one vector is a row vector and the other a column vector (a would be vector and b would be vector2)

a = [1 2 3 4 5 6] b = [ 1 5 8 3 -10 2] idx = bsxfun(@le,a',b)

Now you need to get a bit tricky I guess:

tmp = idx*(10.^[1:numel(b)]') floor(log10(tmp))

Not sure if maybe log2 would be faster, you would need to try it:

tmp = idx*(2.^[1:numel(b)]') floor(log2(tmp))

Jan Simon on 14 Mar 2013

POWER and LOG10 are expensive functions. There must be a solution based on the integer indices also.

Jan Simon on 14 Mar 2013

Yes! When the input `vector2` (as in the original question) is sorted (and `find(., 1, 'last')` implies that it is), the logical matrix created by `bsxfun` contains zeros on the left and ones on the right (or top and bottom?). Then this matrix can be reshaped to a row vector and `strfind` searchs for `[false true]`. Finally the resulting indices must be cleaned up using `mod()` with the number of columns.

## 5 Comments

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/67183#comment_136471

Why do you prefer not to use bsxfun? It seems well suited to the task.

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/67183#comment_136473

because bsxfun is essentially just a slower version of a for loop.

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/67183#comment_136474

That is not true! BSXFUN is highly parallized under the hood. Fastest function you can get.

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/67183#comment_136493

BSXFUN is

nota slower version of a loop. I think ARRAYFUN could earn this description, especially when used with anonymous functions.Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/67183#comment_139512

Having read more about this, I accept my previous statement is wrong and I was getting bsxfun confused with arrayfun.

it seems like bsxfun is what I need. thank you!