【问题标题】:Run different parts of the code in Matlab在 Matlab 中运行代码的不同部分
【发布时间】:2012-11-15 09:14:58
【问题描述】:

我不知道如何正确地问这个问题。希望你能明白我的意思。我在 Matlab 中有一个代码,我有不同的过程。例如,如果我使用某种类型的图像(例如,*.bmp),我必须在 Matlab 中运行一些代码,如果我有另一种类型的图像(*.jpg)我想运行代码的另一部分。

但是,我想做的是在代码的开头 Matlab 询问“什么样的图像?” (例如,使用命令“disp”),然后我会编写“bmp”或“jpg”并运行相关代码。我不喜欢使用循环,只是“写”这个词,它可以识别过程。

我该怎么做?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    使用函数式结构化编程:

    function [some output args] = someFunction([some input args])
    
        answer = [ask question here]
    
        switch lower(answer)
            case 'bmp'
                [some (other) output args] = bmpfunction([some (other) input args]);
            case 'jpg'
                [some (other) output args] = jpgfunction([some (other) input args]);
            otherwise
                error('Unsupported image format.');
        end
    
    end
    
    function [some output args] = bmpfunction([some input args])
        ...
        [bmp operations]
        ...
    end
    
    function [some output args] = jpgfunction([some input args])
        ...
        [jpg operations]
        ...
    end
    

    将所有内容放在一个文件中。然后你可以通过键入

    来调用 Matlab 中的函数
    someFunction([some input args])
    

    当然,[some input args] 等应该在任何地方替换为实际有用的实体 :)

    【讨论】:

      【解决方案2】:

      您可能想要使用以下内容:

      prompt = "What type of image? "
      strResponse = input(prompt, 's')
      
      switch strResponse
      ...
      

      【讨论】:

        【解决方案3】:

        一个优雅的方法是面向对象工作。然后您可以使用函数重载 - 并完全保存 switch 语句。

        像这样:

        classdef JpegImage    
            methods
                function myFunction(obj)
                    ...
                    jpegfunction
                end
            end
        end
        
        classdef BmpImage    
            methods
                function myFunction(obj)
                    ...
                    bmpfunction
                end
            end
        end
        

        然后,您可以在您的代码中使用 myFunction(x) 而无需检查 x 是什么类型。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-08
          • 2011-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-07
          • 1970-01-01
          相关资源
          最近更新 更多