【问题标题】:How to make clear to user that the function's argument to be entered as string in Matlab?如何让用户清楚地知道函数的参数在 Matlab 中作为字符串输入?
【发布时间】:2010-10-03 03:13:23
【问题描述】:

我有以下函数,它的最后一个参数是文本文件的名称:

function [property_without_headers]=gslib_file_to_matlab_var(nModel,nCell,gslib_file_name) % must enter the last argument, gslib_file_name, in single quotes as its treated as a string

if nargin<3, % making third argument optional (code to be executed even when only 2 arguments are provided)
    gslib_file_name=input('Enter the gslib file name: ','s');
end
if length(gslib_file_name)<4 || ~strcmpi(gslib_file_name(end-3:end),'.dat'),
    gslib_file_name=[gslib_file_name '.dat']; % string concatenation
end

%% Reading directly from the .dat files generated from SGEMS and making the data of file as a variable

property_gslib_format=textread(gslib_file_name,'%f\t','headerlines',nModel+2); 
property_without_headers=reshape(property_gslib_format,nModel,nCell)';

现在,通过一般的看法,函数的最后一个要输入的参数似乎是数字。 如何让用户更清楚地知道要输入的最后一个参数(文本文件的名称)应该是字符串格式,即单引号?如果我定义了像下面这样的函数然后我得到 Unexpected MATLAB expression. 的错误:

[property_without_headers]=gslib_file_to_matlab_var(nModel,nCell,'gslib_file_name')

【问题讨论】:

    标签: string matlab function text-files


    【解决方案1】:

    要做的第一件事可能是为函数编写“帮助”,并明确提到最后一个参数必须是字符串。

    您可以使用“ischar()”检查该参数的类型,即:

    if ~ischar(gslib_file_name)
        error('gslib_file_name  should a be string');
    end
    

    【讨论】:

    • 我尝试了你的行,但是如果我写的文件名不带引号,那么它不会继续到这些行。它给出了这个错误:???未定义的函数或变量“poro_models_5wells_gslib_format”。
    • 如果你写它时不带引号,MATLAB 认为它要么是一个变量,要么是一个函数,当两者都不为真时,你会在你的函数 (gslib_file_to_matlab_var) 被调用之前得到一个“未定义的函数或变量”错误.所以我建议你的线路根本没有达到。
    【解决方案2】:

    这就是help documentation 的用途,这也是你的函数的最终用户真正会看到的。更多格式建议可以在here找到。

    【讨论】:

      【解决方案3】:

      如果您的应用程序不需要仅在控制台上运行,我建议使用uigetfile 让用户通过 GUI 对话窗口选择文件。因此,用户会非常清楚您正在查找文件名。

      因此,你会写

      if nargin < 3
           %# ask for a *.dat file
           [fileName,pathName] = uigetfile('*.dat','select gslib file');
           %# check whether the user selected anything
           if fileName == 0
              error('file selection aborted by user')
           end
           %# construct gslib file name from path and file name
           gslib_file_name = fullfile(pathName,fileName);
      end
      

      显然,将函数记录好无论如何都会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-04
        相关资源
        最近更新 更多