FireSky
FireSky

Reputation: 181

My if-else statement / switch case statement is not working matlab

I'm having trouble getting an if-else statement/ switch case statement to work. I have a number and need to find if its between a set of values or another set of values. I've tried all sorts of configurations and nothing is working. (Configuration examples below, PS to save space I'm only showing 2 cases per configuration but I have 15)

date = 1204 or 1203

switch (date)
    case {(1204:1211),(0602:0610)} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {(1126:1203),(0611:0618)} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end    


switch (date)
    case {1204:1211,0602:0610} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {1126:1203,0611:0618} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end  

switch (date)
    case {1204 <= date && date >= 1211,0602 <= date && date >= 0610} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {1126 <= date && date >= 1203,0611 <= date && date >= 0618} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end 

switch (date)
    case {1204 <= date && date >= 1211 || 0602 <= date && date >= 0610} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {1126 <= date && date >= 1203 || 0611 <= date && date >= 0618} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end 

if 1204 <= date && date >= 1211 || 0602 <= date && date >= 0610 % (Dec 4-11th) && (Jun 2-10th)
    d = 0;
elseif 1126 <= date && date >= 1203 || 0611 <= date && date >= 0618 % (Nov 26th - Dec 3rd) && (Jun 11-18th)
    d = 1;
else    
    d = 11;
end 

Upvotes: 0

Views: 257

Answers (1)

David
David

Reputation: 8459

I don't think you can use conditional functions in case expressions. Instead, use an if/elseif/else construction:

if (1204<=date && date<=1211) || (0602<=date && date<=0610) % (Dec 4-11th) && (Jun 2-10th)
    d = 0;
elseif (1126 <= date && date <= 1203) || (0611 <= date && date <= 0618) % (Nov 26th - Dec 3rd) && (Jun 11-18th)
    d = 1;
else
    d = 11;
end

From the documentation:

A case_expression cannot include relational operators such as < or > to compare against the switch_expression. To test for inequality, use if-elseif statements.

Upvotes: 2

Related Questions