Kaelin Colclasure
Kaelin Colclasure

Reputation: 3975

Is there a concise alternative to this cascaded if / elseif / else construct in MATLAB?

I am working on a project which requires making discrete values out of numeric quantities all over the place. At present I'm using cascaded if / elseif / else constructs, for example:

    if M > 6
        evidence{2} = 3;
    elseif M > 2
        evidence{2} = 2;
    else
        evidence{2} = 1;
    end

I want to replace this with a more maintainable (and concise) syntax, but before I come up with my own idiom I would like to know if there is already a convenient function or syntax available in MATLAB. Any suggestions?

Upvotes: 2

Views: 578

Answers (2)

Amro
Amro

Reputation: 124543

How about:

evidence{2} = sum( M > [-inf 2 6] )

Basically, you are searching for the interval in which M lies: (-inf,2], (2,6], (6,+inf)

So even if your values were not 1/2/3, you could then map the range index found to some other values...

Upvotes: 2

Simon
Simon

Reputation: 32873

evidence{2} = 1 + (M > 2) + (M > 6);

but in my opinion, it is less maintainable. Yours is better.

Upvotes: 3

Related Questions