我试图计算整数的长度。
例如:
a = 1.1234; b = 33; c = 100; d = -222;
e = lengthint([a,b,c,d])
预期产出:
e = 1 2 3 3
我试过用这个:
e = max(ceil(log10(abs([a,b,c,d]))),1)
但这是输出:
e = 1 2 2 3
因此,数字是10的倍数存在问题。
答案 0 :(得分:7)
你可以这样做 -
A = [a,b,c,d]
lens = floor(log10(abs(A)))+1
lens(lens<0) = 0 %// Assuming that 0.xx numbers to have zero lengths
样品运行:
案例#1:
>> A = [0.00001234, 1.1234, 33, 10, -222];
>> lens = floor(log10(abs(A)))+1;
>> lens(lens<0) = 0
lens =
0 1 2 2 3
案例#2:
>> A = [-0.00001234, 1.1234 33, 10, -222, 0];
>> lens = floor(log10(abs(A)))+1;
>> lens(lens<0) = 0
lens =
0 1 2 2 3 0
答案 1 :(得分:4)
另一种选择是将它们转换为字符串并检查长度:
cellfun(@(x)length(num2str(abs(fix(x)))),{a,b,c,d});
唯一的复杂因素是你需要单元格来保持你的字符串分开。
来自@Divakar example input的输出:
>> a1 = 0.00001234; a2 = 1.1234; b = 33; c = 100; d = -222;
>> cellfun(@(x)length(num2str(abs(fix(x)))),{a1,a2,b,c,d})
ans =
1 1 2 3 3
因此,1e-5案件显然不会给0。