2017-01-31 75 views
0

我想在MATLAB中实现一个茎和节点算法用于教育目的。在我发布我的代码之前,让我介绍一下我的方法的步骤。让我们考虑,我们有两位数字:茎和叶节点算法

A=[20 12 13 21 56 13 16 17 22 23 24]; 

茎可以通过

stems=fix(A/10) 
stems = 
    2  1  1  2  5  1  1  1  2  2  2 

和叶子可以通过

leaf=fix(mod(A,10)) 

leaf = 

    0  2  3  1  6  3  6  7  2  3  4 

给予我所做的给予,是排序茎和根据那种叶子以及:

[stems, index]=sort(stems,'ascend') 
leaf=leaf(index) 
stems = 
    1  1  1  1  1  2  2  2  2  2  5 
leaf = 
    2  3  3  6  7  0  1  2  3  4  6 

这是基本的想法:

    1. 计数的每个号码的出现频率在stems
  • leaf
  • 采取许多元件

重复此过程对于每个干,我在每一步都缩短了leaf阵列。因此,例如用于stems = 1,我们有[5 1],所以我会

leaf(1:5) 
ans = 
    2  3  3  6  7 
leaf(1:5)=[] 
leaf = 
    0  1  2  3  4  6 

stems = 2又是5次,如此反复:

leaf(1:5) 
ans = 
    0  1  2  3  4 
leaf(1:5)=[] 
leaf = 
    6 

现在为stems = 5,我们有1叶

leaf(1) 
ans = 
    6 

为此,我使用了地图容器,并且创建了以下代码:

function stem_leaf_plot(v) 
if ~isnumeric(v) % check that program will accept array as a integers 
    error('Input V must be numeric'); 

end 
stems=fix(v/10); 
leaf=fix(rem(v,10)); 
[stems, index]=sort(stems,'ascend'); 
leaf=leaf(index); 
string_stems=num2str(stems); 
%% count occurence of each stem 
MAP=containers.Map(); 
n=length(stems); % total element of stems array 
for ii=1:n 
    if isKey(MAP,string_stems(ii)) 
     MAP(string_stems(ii))= MAP(string_stems(ii))+1; 
     else 
     MAP(string_stems(ii))=1; 
    end 
end 
MAP_count=length(MAP); 

stem=num2str(cell2mat(keys(MAP))); 
for jj=1:MAP_count 
    frequency=(MAP(string_stems(jj))); 
    fprintf('leafs of stem %d',stem(jj)); 
    disp(leaf(1:frequency)); 
    leaf(1:frequency)=[]; % delete elements step by step 
end 

end 

然而,我的代码的结果是

stem_leaf_plot(A) 
leafs of stem 32  2  3  3  6 
leafs of stem 49  7  0  1  2  3  4  6 

有什么不对?

+0

我想我意识到问题 –

+0

你为什么在你的例子试图用容器要做到这一点,而不是与数组一样?这似乎很清楚,但你不解释你为什么要使用容器。 – Adriaan

+0

频率计数容器 –

回答

0

经过@Adriaan的建议,我用hist来计算频率,而不是容器。这是我更新的代码:

function stem_leaf_plot(v) 
if ~isnumeric(v) % check that program will accept array as a integers 
    error('Input V must be numeric'); 

end 
stems=fix(v/10); 
leaf=fix(rem(v,10)); 
[stems, index]=sort(stems,'ascend'); 
leaf=leaf(index); 
[a,b]=hist(stems,unique(stems)); 
n=length(a); 
for ii=1:n 
    fprintf('leaf of stem %d is ',b(ii)); 
    leaf(1:a(ii)) 
    leaf(1:a(ii))=[]; 

end 


     >> A=[20 12 13 21 56 13 16 17 22 23 24]; 
>> stem_leaf_plot(A) 
leaf of stem 1 is 
ans = 

    2  3  3  6  7 

leaf of stem 2 is 
ans = 

    0  1  2  3  4 

leaf of stem 5 is 
ans = 

    6 
+0

我可以使输出更漂亮一点吗? –

+0

我不会将输出转储到控制台,而是将其保存到单元格。如果你想要这个教育目的,你应该把'fprintf'声明放在'leaf(1:a(ii))'来摆脱'ans ='。另外,我可以在代码的开头推荐'format compact',以摆脱控制台输出之间的白线。 – Adriaan