Index in position 1 exceeds array bounds. Index must not exceed 1. 出错 qqq1 (第 20 行) disp(kv(1:10,:));
时间: 2024-02-21 08:59:04 浏览: 123
这个错误是因为在读取键值对数组`kv`的前10个元素时,使用了语法`kv(1:10,:)`,但是`kv`数组的长度可能不足10个元素,导致索引越界错误。
为了避免这个错误,可以使用`min`函数获取`kv`数组长度和10的较小值,然后再进行索引,如下所示:
```
disp(kv(1:min(10, size(kv, 1)), :));
```
这样就可以保证索引不会超出数组边界,同时也能够正确地显示前10个键值对。
完整代码示例:
```
passwords = fileread('pswd.txt');
passwords1 = regexp(passwords, '[\s,.?:;!-]+', 'split');
passwords1 = lower(passwords1);
% 统计密码出现次数
m = containers.Map('KeyType', 'char', 'ValueType', 'any');
for i = 1:length(passwords1)
if m.isKey(passwords1{i})
m(passwords1{i}) = m(passwords1{i}) + 1;
else
m(passwords1{i}) = 1;
end
end
% 对密码出现次数进行排序
v = m.values';
k = m.keys';
kv = sortrows([k, v], 2, 'descend');
% 显示前十个常用密码及其出现次数
disp('前十个常用密码及其出现次数:');
disp(kv(1:min(10, size(kv, 1)), :));
% 绘制前十个常用密码的条形图
figure;
sortedCounts = cell2mat(kv(:,2));
sortedPasswords = kv(:,1);
bar(1:min(10, length(sortedCounts)), sortedCounts(1:min(10, length(sortedCounts))));
xticks(1:min(10, length(sortedCounts)));
xticklabels(sortedPasswords(1:min(10, length(sortedCounts))));
xtickangle(45);
xlabel('密码');
ylabel('出现次数');
title(sprintf('前十个常用密码(%s)', [datestr(now) '林浩晟 2022280310']));
```
阅读全文