如何在if循环中传递变量

时间:2015-02-07 20:42:50

标签: matlab

我有几个IF循环,并且有一些我在所有IF循环中重复的东西,例如:

    ` If(someConditions) 
           set(colour,'b', font etc…) 
        end`

    ` If(someConditions) 
           set(colour,'b', font etc…) 
        end`

有什么办法可以让set()方法成为一个全局变量,这样我就可以只传入一个IF循环方法?这就是我所做的,但它不起作用?

   ` 
      variable=colour,'b', font etc…;
        If(someConditions) 
           set('variable'); 
        end`

    ` If(someConditions) 
           set('variable'); 
        end`

2 个答案:

答案 0 :(得分:0)

在Matlab的if条件中没有定义特殊范围,在条件之外定义的所有变量都可以在条件内访问。

我猜你的问题在别的地方。以下代码是否对您有帮助?

figure
h = text(1,1, 'Test');

% Define variables
col = 'b';
varname = 'FontName';
varvalue = 'Arial';

% Condition
if true

    % First syntax, only the value is in a variable
    set(h, 'Color', col);

    % Second syntax, both the name and value of the parameter are in a variable
    set(h, varname, varvalue); 
end

然后,我强烈建议您阅读有关language fondamentals的更多信息。例如,if不应该有一个大写“i”,不需要围绕条件括号,set是一个保留字,不能像你在例程中那样使用。

答案 1 :(得分:0)

您可以创建一个更改所需参数的函数。它的输入参数可以是您正在绘制的图形对象,例如一条线。当然,你可以使功能一般处理许多条件,但是你提供的信息很难猜测。这可能实际上是一种矫枉过正,但它对你有用。

无论如何,这是一个简单的示例,您可以在满足某些条件时更改文本的FontNameColor属性,即您输入if循环。例如,可以使用您绘制的线条的任何属性来完成相同的操作。

function ChangeText(CurrentText) %// The input argument is the handle to the text being displayed. That could be anything such as an axes, a figure, a scatter plot, etc.

FontName = 'Times';
Color = 'r';

set(CurrentText,'FontName',FontName,'Color',Color)

end

然后让你在脚本中用if语句说你遇到感兴趣的条件,你可以简单地调用这个函数:

plot(x,y);

hText = text(x,y, 'Text here')

if SomeCondition

ChangeText(hText) %// Pass the handles of the text as argument to the function

...
end

这是一个非常简单的例子;希望这就是你的意思。您可以使用函数中的switch/case语句对所有内容进行概括,以便您可以检查条件并更改函数内的所有内容。