【问题标题】:What is a stylistically preferred structure for lots of if statements in MATLAB?MATLAB 中许多 if 语句的风格首选结构是什么?
【发布时间】:2019-11-22 16:35:25
【问题描述】:

我有一个代码需要根据用户的要求有条件地绘制多达 6 个图。

用户可以指定一个字符向量,如'123'、'245'、'123456'、'3456'等。如果字符向量中有图形编号,则需要进行绘图。如果它没有出现在字符向量中,则不会绘制。

我能想到的唯一逻辑是:

str = '123456'; 

if contains(str,'1')
    % plot 1
end

if contains(str,'2')
    % plot 2
end

if contains(str,'3')
    $ plot 3
end

% etc... for a total of six if statements

有没有更好的方法在代码中实例化这个逻辑?我不能 switchelseif 因为通常需要制作超过 1 个地块。

编辑:我无法使用 for 循环解决方案

for i = 1:6
    if contains(str,i)
        % plot i
    end
end

因为在% plot i 内,我必须执行相同的一组 6 个 if 语句来确定传递给 plot 命令的内容。

【问题讨论】:

  • 注意:我需要/选择拥有超过 6 个地块。
  • 不同地块的代码是否有相似之处?
  • 一些,但我认为没有一个是可以利用的。如果我做了一个 for 循环和一个关于是否应该制作第 i 个图的条件语句,我将不得不执行 if 语句来确定将什么传递给 plot 命令以及如何格式化图。

标签: matlab if-statement conditional-statements


【解决方案1】:

if 语句序列的解决方案很好。它高效且易于实施。如果您希望您的用户也能够更改绘图的顺序,通过以不同的顺序给出str,您必须使用带有switch 语句的for 循环:

for c = str
  switch c
    case '1'
      % plot 1
    case '2'
      % plot 2
    % ...
  end
end

避免代码复制的稍微复杂一点的解决方案如下:

plotdata(1).x = 1:100;
plotdata(1).y = randn(100,1);
plotdata(1).format = {'linewidth',2,'marker','o','color','m'};
plotdata(1).title = 'series 1';

plotdata(2).x = ...

for c = str
  indx = c - '0';
  figure
  plot(plotdata(indx).x,plotdata(indx).y,plotdata(indx).format{:});
  title(plotdata(indx).title);
  % maybe more formatting commands here
end

如果每个绘图使用不同的命令,您可以将匿名函数放入数据结构中,如下所示:

plotdata(1).cmd = @()plot(1:100,randn(100,1),'linewidth',2,'marker','o','color','m');
plotdata(1).title = 'series 1';

%...

figure
plotdata(indx).cmd();
title(plotdata(indx).title);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 2011-02-02
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多