mark grey
mark grey

Reputation: 1

SWITCH expression must be a scalar or character vector constant

Apologies for any mistake am still learning programming and also in MATLAB. The code Below is written to satisfy the fact that if the Playerlocation is either ([0, 1, 2, 3]) the case should display the text (You are in a Sunny Field) and I will be adding to it if Playerlocation is not = ([0, 1, 2, 3]) it should display display a different text ( You are not in a Sunny Field) I would appreciate it if am corrected and thanks in advance

function describeLocation()
        clear all 
        close all

        global playerLocation;

     playerLocation = ([0, 1, 2, 3]);

    switch (playerLocation)

        case 0
            Text ='You are in a Sunny Field';
        disp(Text);

        case 1
            Text1 ='You are in a Sunny Field1';
        disp(Text1);

        case 2
            Text2 ='You are in a Sunny Field2';
        disp(Text2);

        case 3 
            Text3 ='You are in a Sunny Field3';
        disp(Text3);


    end  

Upvotes: 0

Views: 7949

Answers (1)

Suever
Suever

Reputation: 65430

The input to the switch statement must be a scalar or character array (as clearly specified by the error message). In your case, playerLocation is an array which causes the error.

Rather than passing the entire array to switch you should loop through the array and pass each scalar member separately

for k = 1:numel(playerLocation)
    switch (playerLocation(k))
    case 0
        Text ='You are in a Sunny Field';
        disp(Text);
    case 1
        Text1 ='You are in a Sunny Field1';
        disp(Text1);
    case 2
        Text2 ='You are in a Sunny Field2';
        disp(Text2);
    case 3 
        Text3 ='You are in a Sunny Field3';
        disp(Text3);
    end
end  

To shorten this up, you can include multiple values in your case statements

switch(playerLocation(k))
case {0, 1, 2, 3}
    disp('You are in a sunny field');
otherwise
    disp('You are not in a sunny field');
end

If you're trying to check if playerLocation is exactly [0, 1, 2, 3], then a switch statement isn't what you want. You would just want a normal if statement

if isequal(playerLocation, [0, 1, 2, 3])
    disp('You are in a sunny field')
else
    disp('You are not in a sunny field');
end

Upvotes: 2

Related Questions