【问题标题】:Writing string variables in if-else statements in Matlab在 Matlab 中的 if-else 语句中编写字符串变量
【发布时间】:2019-07-08 11:23:18
【问题描述】:

这可能是一个微不足道的问题,但我想在 Matlab 中编写一个简单的 for 循环,将字符串变量用于不同的情况。

在 Python 中,很简单,

from numpy import cos, sin, pi

dist = 'markovian'

x = pi/7

if dist == 'lorentzian':
    z = sin(x)
    print(z)
elif dist == 'markovian':
    z = cos(x)
    print(z)
else:
    z = sin(x) + cos(x)
    print(z)

我在 Matlab 中尝试过

dist = 'markovian';

x = pi/7;

if dist == strcmpi('lorentzian','true')
    z = sin(x)
elseif dist == strcmpi('markovian','true')
    z = cos(x)
else
    z = sin(x) + cos(x)
end

但它不计算zstrcmpi 我做错了什么?

【问题讨论】:

    标签: matlab for-loop boolean


    【解决方案1】:

    使用 strcmpiif / else

    函数strcmpi 比较两个字符串忽略大小写并返回一个逻辑值。因此,您需要按如下方式使用它:

    dist = 'markovian';
    x = pi/7;
    if strcmpi(dist, 'lorentzian')
        z = sin(x)
    elseif strcmpi(dist, 'markovian')
        z = cos(x)
    else
        z = sin(x) + cos(x)
    end
    

    使用switch

    使用switch 语句可能会使代码更清晰。您可以使用lower 来实现不区分大小写。

    dist = 'markovian';
    x = pi/7;
    switch lower(dist)
        case 'lorentzian'
            z = sin(x)
        case 'markovian'
            z = cos(x)
        otherwise
            z = sin(x) + cos(x)
    end
    

    无分支

    这是一种避免分支的替代方法。如果您只有两个或三个选项,则此方法会不必要地复杂,但如果选项很多,则可能更适合紧凑性甚至可读性。

    这通过在 char 向量元胞数组中查找所选选项的索引(如果存在)来工作;并使用feval 从函数句柄元胞数组中计算相应的函数:

    names = {'lorentzian', 'markovian'}; % names: cell array of char vectors
    funs = {@(x)sin(x), @(x)cos(x), @(x)sin(x)+cos(x)}; % functions: cell array of handles.
                                                        % Note there is one more than names
    dist = 'markovian';
    x = pi/7;
    [~, ind] = ismember(lower(dist), names); % index of dist in names
    ind = ind + (ind==0)*numel(funs); % if 0 (dist not in names), select last function
    feval(funs{ind}, x)
    

    【讨论】:

      【解决方案2】:

      MATLAB >= R2016b 中的另一个选项是对文本数据使用string 而不是charstring 可让您使用 == 进行比较,如下所示:

      dist = "markovian"
      
      x = pi/7
      
      if dist == "lorentzian"
          z = sin(x)
      elseif dist == "markovian"
          z = cos(x)
      else
          z = sin(x) + cos(x)
      end
      

      【讨论】:

      • 嗯,对我来说不是完全清楚他们想要不区分大小写 - 当然== 在 Python 中是区分大小写的吗?在我看来,这就是他们的出发点。
      • 你是对的。 Python 的 == 区分大小写,但 Matlab 的 strcmpi 不区分大小写。所以不清楚他们想要什么
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2018-01-09
      • 2015-07-28
      • 1970-01-01
      • 2015-12-24
      • 2023-03-24
      相关资源
      最近更新 更多