คุณสามารถใช้ dec2base
และแทนที่อักขระด้วยตัวเลข:
x = 23;
b = 12;
[~, result] = ismember(dec2base(x,b), ['0':'9' 'A':'Z']);
result = result -1;
ให้
>> result
result =
1 11
ใช้งานได้กับ ฐานสูงสุด 36 เท่านั้น เนื่องจาก dec2base
ข้อจำกัด
สำหรับ ฐานใดๆ (อาจมากกว่า 36) คุณต้องทำการแปลงด้วยตนเอง ฉันเคยเขียนฟังก์ชัน base2base
เพื่อทำเช่นนั้น (โดยพื้นฐานแล้วเป็นการหารยาว) ควรป้อนตัวเลขเป็นเวกเตอร์ของตัวเลขในฐานเริ่มต้น ดังนั้นคุณต้องมี dec2base(...,10)
ก่อน ตัวอย่างเช่น:
x = 125;
b = 6;
result = base2base(dec2base(x,10), '0':'9', b); % origin nunber, origin base, target base
ให้
result =
3 2 5
หรือหากต้องการระบุจำนวนหลัก:
x = 125;
b = 6;
d = 5;
result = base2base(dec2base(x,10), '0':'9', b, d)
result =
0 0 3 2 5
แก้ไข (15 สิงหาคม 2017): แก้ไขข้อบกพร่องสองประการ: การจัดการอินพุตที่ประกอบด้วย "ศูนย์" ทั้งหมด (ขอบคุณ @Sanchises เพื่อการสังเกต) และเว้นเอาต์พุตให้เหลืออย่างเหมาะสมด้วย "ศูนย์" หากจำเป็น
function Z = base2base(varargin)
% Three inputs: origin array, origin base, target base
% If a base is specified by a number, say b, the digits are [0,1,...,d-1].
% The base can also be directly an array with the digits
% Fourth input, optional: how many digits the output should have as a
% minimum (padding with leading zeros, i.e with the first digit)
% Non-valid digits in origin array are discarded.
% It works with cell arrays. In this case it gives a matrix in which each
% row is padded with leading zeros if needed
% If the base is specified as a number, digits are numbers, not
% characters as in `dec2base` and `base2dec`
if ~iscell(varargin{1}), varargin{1} = varargin(1); end
if numel(varargin{2})>1, ax = varargin{2}; bx=numel(ax); else bx = varargin{2}; ax = 0:bx-1; end
if numel(varargin{3})>1, az = varargin{3}; bz=numel(az); else bz = varargin{3}; az = 0:bz-1; end
Z = cell(size(varargin{1}));
for c = 1:numel(varargin{1})
x = varargin{1}{c}; [valid, x] = ismember(x,ax); x = x(valid)-1;
if ~isempty(x) && ~any(x) % Non-empty input, all zeros
z = 0;
elseif ~isempty(x) % Non-empty input, at least a nonzero
z = NaN(1,ceil(numel(x)*log2(bx)/log2(bz))); done_outer = false;
n = 0;
while ~done_outer
n = n + 1;
x = [0 x(find(x,1):end)];
y = NaN(size(x)); done_inner = false;
m = 0;
while ~done_inner
m = m + 1;
t = x(1)*bx+x(2);
r = mod(t, bz); q = (t-r)/bz;
y(m) = q; x = [r x(3:end)];
done_inner = numel(x) < 2;
end
y = y(1:m);
z(n) = r; x = y; done_outer = ~any(x);
end
z = z(n:-1:1);
else % Empty input
z = []; % output will be empty (unless user has required left-padding) with the
% appropriate class
end
if numel(varargin)>=4 && numel(z)<varargin{4}, z = [zeros(1,varargin{4}-numel(z)) z]; end
% left-pad if required by user
Z{c} = z;
end
L = max(cellfun(@numel, Z));
Z = cellfun(@(x) [zeros(1, L-numel(x)) x], Z, 'uniformoutput', false); % left-pad so that
% result will be a matrix
Z = vertcat(Z{:});
Z = az(Z+1);
person
Luis Mendo
schedule
18.11.2016
floor
,^
และ/
เป็นเวกเตอร์อยู่แล้ว ไม่จำเป็นต้องวนซ้ำ - person excaza   schedule 18.11.2016