美好的一天!有什麼辦法可以告訴matlab函數的輸入是一個字符串。例如thisisastring(11A)
Matlab字符串輸入
我的預期輸入是二進制字符串(010011101)和十六進制(1B)。你能幫助我嗎?
美好的一天!有什麼辦法可以告訴matlab函數的輸入是一個字符串。例如thisisastring(11A)
Matlab字符串輸入
我的預期輸入是二進制字符串(010011101)和十六進制(1B)。你能幫助我嗎?
與許多語言不同,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
要檢查參數的數據類型在函數中,並聲明它們符合其他標準(如數組維度和值的約束),請使用validateattributes。這非常方便,並且是標準的matlab。