Why would command syntax split string when using double quotes?

5 ビュー (過去 30 日間)
Xingwang Yong
Xingwang Yong 2021 年 10 月 28 日
コメント済み: Walter Roberson 2021 年 10 月 28 日
disp 'str ing' % good
disp "str ing" % error, Too many input arguments
I am on R2020a. It seems that the latter is equivalent to
disp str ing
I thought, at least
disp "str ing"
should be interpreted as
disp('"str ing"')
why would matlab split the string into several parts?

採用された回答

Walter Roberson
Walter Roberson 2021 年 10 月 28 日
Not exactly. The latter is equivalent to disp('"str', 'ing"')
N 'str ing'
nargin = 1 varargin{1} = str ing
N "str ing"
nargin = 2 varargin{1} = "str varargin{2} = ing"
function N(varargin)
fprintf('nargin = %d\n', nargin);
celldisp(varargin)
end
why would matlab split the string into several parts?
Because that is what is documented:
With command syntax, MATLAB passes all inputs as character vectors (that is, as if they were enclosed in single quotation marks) and does not assign outputs to variables. To pass a data type other than a character vector, use the function syntax. To pass a value that contains a space, you have two options. One is to use function syntax. The other is to put single quotes around the value. Otherwise, MATLAB treats the space as splitting your value into multiple inputs.
In order for disp "str ing" to be treated as disp("str ing") then that would directly violate the rule that MATLAB passes all inputs as character vectors.
It does not explain why MATLAB does not convert the string into a character vector, as-if disp('str ing') had been called, but the documentation never implies anything like that would happen. Instead, the documentation talks only about single-quotes to include blanks, not about double-quotes.
It would not be unreasonable for MATLAB to be enhanced to handle double-quoted strings... but it is not a bug that it does not do so at the moment.
  2 件のコメント
Xingwang Yong
Xingwang Yong 2021 年 10 月 28 日
編集済み: Xingwang Yong 2021 年 10 月 28 日
In function syntax, double quotes and single quotes make no difference, i.e. disp("str ing") == disp('str ing'). I thought they would be the same in command syntax, which is not the case though. Although documented, this is counterintuitive.
Walter Roberson
Walter Roberson 2021 年 10 月 28 日
It is not correct that single quotes or double quotes make no difference. Consider
N('str ing')
numel = 7 #1: s #2: t #3: r #4: #5: i #6: n #7: g
N("str ing")
numel = 1 #1: str ing
function N(S)
NE = numel(S);
fprintf('numel = %d\n', NE);
for K = 1 : NE
fprintf('#%d: %s\n', K, S(K));
end
end
Character vectors with single quotes are not the same as string objects with double quotes

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by