问题描述:

Good Day! Is there any way that I can tell matlab that the input to my function is a string. e.g. thisisastring(11A)

My expected inputs are string of binary (010011101) and hexadecimal(1B). Can you help me with this?

网友答案:

ischar and iscellstr can tell you if the input is a char array or cell array containing strings (char arrays).

bin2dec and hex2dec will convert strings to numbers.

网友答案:

To check data types of arguments in functions, and to assert they meet other criteria like array dimensions, and constraints on values, use validateattributes. It's very convenient, and standard matlab.

网友答案:

Unlike many languages, Matlab is dynamically typed. So there really is no way to tell Matlab that a function will always be called with a string input. If needed, you can check the type of the input at the beginning of a function, but that is not always the right answer. So, for example, in Java you may write something like this:

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

In Matlab you have two options. First, you can write your code just assuming that it is a string, like this:

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)

Or, if you are paranoid and want to write robust code

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
相关阅读:
Top