我在MATLAB中寻找一种非常快速的方法来搜索整数内的特定数字,理想情况是在给定位置。例如:
简单案例......
我想查看一个整数数组并返回包含数字1的所有内容,例如1234,4321,6515,847251737等
更复杂的案例......
我想循环遍历整数数组并返回包含第三位数字1的所有数据,例如6218473,541846,3115473但不会返回175846。
有什么想法吗?
答案 0 :(得分:4)
这里已经有了一些答案,我会把我的尝试扔进锅里。
转换为字符串可能很昂贵,因此如果可以避免,则应该是。
n = 1:100000; % sample numbers
m = 3; % digit to check
x = 1; % number to find
% Length of the numbers in digits
num_length = floor(log10(abs(n)))+1;
% digit (from the left) to check
num_place = num_length-m;
% get the digit
digit_in_place = mod(floor(abs(n)./(10.^num_place)),10);
found_number = n(digit_in_place==x);
答案 1 :(得分:3)
通过强制转换为字符串,矢量化技巧只是为了确保x
是一个列向量。 x(:)
保证这一点。您还需要左对齐字符串,这些字符串由格式说明符'%-d'
完成,其中-
用于左对齐,d
用于整数:
s = num2str(x(:), '%-d');
ind = s(:,3)=='1'
这也可以让您轻松解决第一种情况:
ind = any(s=='1',2)
在任何一种情况下都可以恢复原来的号码:
x(ind)
答案 2 :(得分:1)
到达那里的一种方法是将您的数字转换为字符串,然后检查该字符串的第3个位置是否为'1'
。它在循环中工作得很好,但我相信还有一个矢量化解决方案:
numbers = [6218473, 541846, 3115473, 175846]'
returned_numbers = [];
for i = 1:length(numbers)
number = numbers(i);
y = sprintf('%d', number) %// cast to string
%// add number to list, if its third character is 11
if strcmp(y(3), '1')
returned_numbers = [returned_numbers, number];
end
end
% // it returns:
returned_numbers =
6218473 541846 3115473
答案 3 :(得分:1)
<强>代码强>
%// Input array
array1 = [-94341 1234 4321 6515 847251737 6218473 541846 3115473 175846]
N = numel(array1); %// number of elements in input array
digits_sep = num2str(array1(:))-'0'; %//' Seperate the digits into a matrix
%// Simple case
output1 = array1(any(digits_sep==1,2))
%// More complex case output
col_num = 3;
%// Get column numbers for each row of the digits matrix and thus
%// the actual linear index corresponding to 3rd digit for each input element
ind1 =sub2ind(size(digits_sep),1:N,...
size(digits_sep,2)-floor(log10(abs(array1))-col_num+1));
%// Select the third digits, check which ones have `1` and use them to logically
%// index into input array to get the output
output2 = array1(digits_sep(ind1)==1)
代码运行 -
array1 =
-94341 1234 4321 6515 847251737 6218473 541846 3115473 175846
output1 =
-94341 1234 4321 6515 847251737 6218473 541846 3115473 175846
output2 =
6515 6218473 541846 3115473