Matlab字符串输入

时间:2012-09-27 03:32:22

标签: matlab

美好的一天!有什么方法可以告诉matlab我的函数输入是一个字符串。例如thisisastring(11A)

我的预期输入是二进制(010011101)和十六进制(1B)的字符串。你能帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

ischariscellstr可以告诉您输入是char数组还是包含字符串的单元格数组(char数组)。

bin2dechex2dec会将字符串转换为数字。

答案 1 :(得分:2)

要检查函数中参数的数据类型,并断言它们符合其他条件,如数组维度和值约束,请使用validateattributes。这是非常方便的,也是标准的matlab。

答案 2 :(得分:1)

与许多语言不同,Matlab是动态类型的。因此,实际上没有办法告诉Matlab将始终使用字符串输入调用函数。如果需要,您可以在函数开头检查输入的类型,但这并不总是正确的答案。因此,例如,在Java中,您可以编写如下内容:

public class SomeClass {
    public static void someMethod(String arg1) {
        //Do something with arg1, which will always be a String
    }
}

在Matlab中,您有两种选择。首先,您可以编写代码,只需假设它是一个字符串,如下所示:

function someFunction(arg1)
%SOMEFUNCTION  Performs basic string operations
%    SOMEFUNCTION('INPUTSTRING')  performs an operation on 'INPUTSTRING'.

%Do something with arg1, which will always be a string.  You know 
%    this because the help section indicates the input should be a string, and 
%    you trust the users of this function (perhaps yourself)

或者,如果你是偏执狂并希望编写健壮的代码

function someFunction(arg1)
%SOMEFUNCTION  Performs basic string operations
%    SOMEFUNCTION('INPUTSTRING')  performs an operation on 'INPUTSTRING'.

if ~ischar(arg1)
    %Error handling here, where you either throw an error, or try 
    %    and guess what your user intended. for example
    if isnumeric(arg1) && isscalar(arg1)
        someFunction(num2str(arg1));
    elseif iscellstr(arg1)
        for ix = 1:numel(arg1)
            someFunction(arg1{1});
        end
    else
        error(['someFunction requires a string input.  ''' class(arg1) ''' found.'])
    end
else
    %Do somethinbg with arg1, which will always be a string, due to the IF statement
end