I am wondering whether I can do the following efficiently in Matlab. Writing a naive loop for the problem is pretty straightforward, but I am trying to find whether there are any specialized functions one could use (perhaps arrayfun / accumarray (?) — both of which I have great trouble in understanding!) Thanks in advance.
Let’s say I have two vectors as follows (in Matlab):
A = [15 4 9 6 7 5 11 3 14];
B = [2 7 13];
I would like to do the following:
- Sort
B, if not sorted already. - For every successive windows in
B(i.e.,[2,7],[7,13]), find the corresponding elements in A that lie within the window. - In this “partitioned”
A, decrement by 1 n-times from those elements inAthat lie in the n-th window ofB.
Example: In the above case, the first window of B is [2,7]. The elements in A that lie within this window are [5,4,3,6]. As they lie within the first window of B, I need to decrement 1, one time from each of these elements. The new A will look like the following after this operation:
A = [15 3 9 5 7 4 11 2 14];
Can this problem be reduced to a few function calls in Matlab or one should go through the naive loop business anyway? Thanks!
This can be done quite easily by using the
histcfunction to determine in what bin (what you called “window”) the values are.edit:
I noticed my solution is different from yours, but I suspect you made a mistake in your calculation. Do you have to subtract
2from the values within the second bin or do you leave them as-is? If you only want to change the values in the first bin, the last line should readA(bin==1) = A(bin==1) - 1.To change in what bin a value on the edge of a bin should end up, you can try to add/subtract
epsfromB.