如何确定输入是 Matlab 中的比率还是浮点数?
How to determine if input is a ratio or float in Matlab?
我需要批处理 混合单位的文本文件, 即整数比率和浮点数(它们是未知有理数或无理数的缩放对数近似值)。 Matlab 如何检测哪个输入是哪个?会扫描“.”或者'/'字符最好?
252.63
4/3
757.89
2/1
在这个例子中,我认识到数字以递增顺序表示值(但以混合单位表示,这在我的研究领域很典型),我将以不同于 4/3 和 2/1 的方式处理 252.63 和 757.89 .
我没有在 Matlab 中找到像 isa(x, 'rat')
这样的函数,其中 x 是上面列表中的任何一行,而 'rat' 会比。
Matlab 可以非常简单地搜索特定字符的字符串。
slashmask = str == '/'; % returns false for every character in str that's not a slash, and true for every one that is.
slashdetected = any(slashmask); % returns false if no character is a slash.
如果您需要做的只是获取比率并计算它,然后以与浮点数相同的方式使用它,您只需使用 "eval" 函数来检索等效的浮点数。
感谢您的提示。在你的帮助下,我解决了这个问题(每行数据文件):
x = fgetl(fileId);
if isnan(str2double(x)) == true
% Interpret string as ratio number
x = str2num(x);
% then convert to musical cents,
s(i) = log(x) / log(2) * 1200;
else
% convert string to float, already in cents.
s(i) = str2double(x);
end
我需要批处理 混合单位的文本文件, 即整数比率和浮点数(它们是未知有理数或无理数的缩放对数近似值)。 Matlab 如何检测哪个输入是哪个?会扫描“.”或者'/'字符最好?
252.63
4/3
757.89
2/1
在这个例子中,我认识到数字以递增顺序表示值(但以混合单位表示,这在我的研究领域很典型),我将以不同于 4/3 和 2/1 的方式处理 252.63 和 757.89 .
我没有在 Matlab 中找到像 isa(x, 'rat')
这样的函数,其中 x 是上面列表中的任何一行,而 'rat' 会比。
Matlab 可以非常简单地搜索特定字符的字符串。
slashmask = str == '/'; % returns false for every character in str that's not a slash, and true for every one that is.
slashdetected = any(slashmask); % returns false if no character is a slash.
如果您需要做的只是获取比率并计算它,然后以与浮点数相同的方式使用它,您只需使用 "eval" 函数来检索等效的浮点数。
感谢您的提示。在你的帮助下,我解决了这个问题(每行数据文件):
x = fgetl(fileId);
if isnan(str2double(x)) == true
% Interpret string as ratio number
x = str2num(x);
% then convert to musical cents,
s(i) = log(x) / log(2) * 1200;
else
% convert string to float, already in cents.
s(i) = str2double(x);
end