Let's say that you had a small vector mt_carr.
mt_carr = [0 0.25 0.25 0.25];
What's the result of computing the cumsum of mt_carr?
cumsum(mt_carr)
ans =
0 0.2500 0.5000 0.7500
Suppose that the rand function were to return a value like 0.9:
Let's run your code using those variables. [I've fixed R instead of using rand to make it easy to reproduce the behavior you're seeing.]
y = find(R < cumsum(mt_carr), 1, 'first')
y =
1×0 empty double row vector
This makes sense. None of the elements of the cumsum vector are greater than the value of R.
What happens if I try to assign that index back into an element of a vector?
x = 1:5;
x(1) = find(R < cumsum(mt_carr), 1, 'first')
I receive a different error message than the one you received when I run this code in release R2018a. We enhanced that error message to be a little bit easier to understand at some point, but I don't remember the exact release. The error message as displayed in the Command Window doesn't have a line break, but I didn't want you to have to scroll to see the whole thing.
Unable to perform assignment because the left and right sides
have a different number of elements.
The left side x(1) refers to 1 element of x. The right side (the find call) returns an array with 0 elements. This won't work.
I can think of at least two ways you could make this work. The first would be to ensure that the largest element of mt_carr was greater than or equal to the maximum value rand can return. If you do this, your code will need to handle the situation where your vector contains a value greater than the number of elements in mt_carr.
x(1) = find(R < [cumsum(mt_carr) Inf], 1, 'first')
The second way is to use the discretize function. This will return NaN if rand returns a value outside the range of the edges vector cumsum(mt_carr).
x(1) = discretize(R, cumsum(mt_carr))
Best Answer