Matlab 开关表达式必须是标量或字符向量常量

Matlab 开关表达式必须是标量或字符向量常量,matlab,matlab-guide,Matlab,Matlab Guide,我仍在学习编程,也在学习MATLAB。下面的代码是为了满足这样一个事实,即如果Playerlocation为([0,1,2,3]),则案例应该显示文本(您在阳光域中),如果Playerlocation不是=([0,1,2,3]),我将添加到它中,它应该显示不同的文本(您不在阳光域中)如果我能更正并提前感谢您,我将不胜感激 function describeLocation() clear all close all global playerL

我仍在学习编程,也在学习MATLAB。下面的代码是为了满足这样一个事实,即如果Playerlocation为([0,1,2,3]),则案例应该显示文本(您在阳光域中),如果Playerlocation不是=([0,1,2,3]),我将添加到它中,它应该显示不同的文本(您不在阳光域中)如果我能更正并提前感谢您,我将不胜感激

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  

switch
语句的输入必须是标量或字符数组(错误消息中明确指定)。在您的例子中,
playerLocation
是一个导致错误的数组

您不应该将整个数组传递给
开关
,而应该循环遍历数组并分别传递每个标量成员

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  
为了缩短时间,您可以在
case
语句中包含多个值

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
如果您试图检查
playerLocation
是否正好是
[0,1,2,3]
,则
开关
语句不是您想要的。您只需要一个正常的
if
语句

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

switch
语句的输入必须是标量或字符数组(错误消息中明确指定)。在您的例子中,
playerLocation
是一个导致错误的数组

您不应该将整个数组传递给
开关
,而应该循环遍历数组并分别传递每个标量成员

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  
为了缩短时间,您可以在
case
语句中包含多个值

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
如果您试图检查
playerLocation
是否正好是
[0,1,2,3]
,则
开关
语句不是您想要的。您只需要一个正常的
if
语句

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