lokilindo
lokilindo

Reputation: 702

How can I simplify this MatLab code?

I would like to know if there is a way to get rid of the inner for loop

for i = 1:size(VALUES)
    for k = 2:bins+1
        if VALUES(i) < Arr(k)
            answer_list(i) = find(Arr == Arr(k)) - 1;
            break
        end
    end
end

VALUES is a file with 100 doubles from 2 to 4
Arr is an array with 4 values, starting at VALUES min a step of 1 and ends at VALUES max
bins is Arr's length - 1
and answer_list is a column of numbers VALUES long that hold the discrete value depending on the size of the bins variable.

Upvotes: 1

Views: 96

Answers (1)

EBH
EBH

Reputation: 10450

I think this is what you look for (in comments are the references to the original lines in your code):

out = bsxfun(@lt,VALUES(:).',Arr(:)) % if VALUES(i) < Arr(k):
out2 = size(out,1)-cumsum(out,1); % find(Arr == Arr(k)) - 1;
answer_list = out2(end,any(out,1)).';

This replaces the whole code, not only the inner loop.

Upvotes: 2

Related Questions