String 如何向用户说明函数的参数在Matlab中输入为字符串?
我有以下函数,其最后一个参数是文本文件的名称:String 如何向用户说明函数的参数在Matlab中输入为字符串?,string,matlab,function,text-files,String,Matlab,Function,Text Files,我有以下函数,其最后一个参数是文本文件的名称: 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 o
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)';
要做的第一件事可能是为函数编写帮助,并明确指出最后一个参数必须是字符串 您可以使用ischar检查该参数的类型,即:
if ~ischar(gslib_file_name)
error('gslib_file_name should a be string');
end
这就是它的用途,这也是函数的最终用户真正将要看到的。可以找到更多的格式建议。如果应用程序不需要仅在控制台上运行,我建议使用,让用户通过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
显然,很好地记录函数将有所帮助。我尝试了您的代码行,但是如果我写的文件名没有引号,那么它就不会继续到这些代码行。它给出了这个错误:???未定义的函数或变量“poro_models_5wells_gslib_format”。如果编写时没有引号,MATLAB会认为它是一个变量或函数,如果两者都不是真的,则在调用函数gslib_file_to_MATLAB_var之前会出现未定义的函数或变量错误。所以我推荐给你的那几行电话根本就没人接。
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