如何使用 Matlab 计算数据集中一行的相对频率?
How can I calculate the relative frequency of a row in a data set using Matlab?
我是 Matlab 新手,有一个基本问题。
我有这个数据集:
1 2 3
4 5 7
5 2 7
1 2 3
6 5 3
我正在尝试根据上面的数据集计算相对频率
具体计算x=1,y=2,z=3
的相对频率
我的代码是:
data = load('datasetReduced.txt')
X = data(:, 1)
Y = data(:, 2)
Z = data(:, 3)
f = 0;
for i=1:5
if X == 1 & Y == 2 & Z == 3
s = 1;
else
s = 0;
end
f = f + s;
end
f
r = f/5
结果为 0。
怎么修改代码??
谢谢,
正书
您的问题很可能是您 comparing floating point numbers using the ==
operator which is likely to fail due to floating point errors.
一个更快的方法是使用 ismember
和 'rows'
选项,这将产生一个 logical
数组,然后您可以 sum
得到匹配的总行数除以总行数。
tf = ismember(data, [1 2 3], 'rows');
relFreq = sum(tf) / numel(tf);
我想你想计算每个实例的频率,所以试试这个
data = [1 2 3
4 5 7
5 2 7
1 2 3
6 5 3];
[counts,centers] = hist(data , unique(data))
其中 centers 是您的唯一实例,counts 是每个实例的计数。结果应该如下:
counts =
2 0 0
0 3 0
0 0 3
1 0 0
1 2 0
1 0 0
0 0 2
centers =
1 2 3 4 5 6 7
这意味着您有 7 个唯一实例,从 1 到 7,第一列有两个 1,第二列和第三列没有任何 1,依此类推
我是 Matlab 新手,有一个基本问题。
我有这个数据集:
1 2 3
4 5 7
5 2 7
1 2 3
6 5 3
我正在尝试根据上面的数据集计算相对频率 具体计算x=1,y=2,z=3
的相对频率我的代码是:
data = load('datasetReduced.txt')
X = data(:, 1)
Y = data(:, 2)
Z = data(:, 3)
f = 0;
for i=1:5
if X == 1 & Y == 2 & Z == 3
s = 1;
else
s = 0;
end
f = f + s;
end
f
r = f/5
结果为 0。 怎么修改代码??
谢谢,
正书
您的问题很可能是您 comparing floating point numbers using the ==
operator which is likely to fail due to floating point errors.
一个更快的方法是使用 ismember
和 'rows'
选项,这将产生一个 logical
数组,然后您可以 sum
得到匹配的总行数除以总行数。
tf = ismember(data, [1 2 3], 'rows');
relFreq = sum(tf) / numel(tf);
我想你想计算每个实例的频率,所以试试这个
data = [1 2 3
4 5 7
5 2 7
1 2 3
6 5 3];
[counts,centers] = hist(data , unique(data))
其中 centers 是您的唯一实例,counts 是每个实例的计数。结果应该如下:
counts =
2 0 0
0 3 0
0 0 3
1 0 0
1 2 0
1 0 0
0 0 2
centers =
1 2 3 4 5 6 7
这意味着您有 7 个唯一实例,从 1 到 7,第一列有两个 1,第二列和第三列没有任何 1,依此类推