【问题标题】:Matlab Looping Issue for counting similarity score用于计算相似度分数的 Matlab 循环问题
【发布时间】:2015-03-25 08:13:58
【问题描述】:

我有 3 组不同长度和大小的数据(AA、B1 和 C1)。我的代码的目的是能够计算数据之间的相似度得分,例如 AA 和 B1、AA 和 C1、B1 和 C1 之间的相似度得分。所以下面是我的代码,它应该能够计算相似度分数,但是循环存在一些问题。对于每对不同长度的数据,只选择最高值。输出应为 AA-B1: 0.2226, AA-C1: 0.2037 和 B1-C1: 0.1111,表示每对的相似度得分。

实际上,我的代码尤其是max_val{i} 的输出是根据对的大小来假设的。例如,大小为 1 x 2 的对在 max_val 输出中应该有一个值,而不是三个。谢谢。

A1={[4,3,4,3,3]};
A2={[3,1,2,4]};
A3={[1,2,4]};
AA=[A1,A2,A3];
B1={[2,2,4,4]};
C1={[4,4,4,3,2,2]};

set={[AA],[B1],[C1]};
comb_set=nchoosek(set,2); %combinations of two sets

for h=1:size(comb_set,1)
comb_pair=comb_set(h,:)';
sets=comb_pair;

cat=horzcat(sets{:});
c=reshape(repmat(sets{1},numel(sets{2}),1),numel(sets{1})*numel(sets{2}),1);
d=repmat(sets{2}(:),length(sets{1}),1);
pairs=[c d];
ind=cellfun(@numel,pairs(:,1)) > cellfun(@numel,pairs(:,2));
pairs(ind,[1 2]) = pairs(ind,[2 1]) %possible pairs of the row of subset
p=cell(size(pairs,1),1);

for i=1:size(pairs,1)
%the two vectors
[a,b]=deal(pairs{i,:});
%sliding window indices, and compute the sum
idx=hankel(1:numel(a),numel(a):numel(b));
count_minus{i}=bsxfun(@minus,b(idx.'),a);  %count minus between pairs
count_total{i}=numel(a)+numel(b);  %count total
count_intersect{i}=sum(count_minus{i}'==0)';  %count no. of intersection
union{i}=count_total{i}-count_intersect{i};  %union
subset{i}=count_intersect{i}./union{i}; %subset each pair similarity score
max_val{i}=max(subset{i}) %maximum similarity score
bsum=cellfun(@(x) sum(x),max_val);
total{i}=sum(bsum~=0);
average=sum(bsum) / total{i}
end
end

【问题讨论】:

    标签: matlab loops for-loop


    【解决方案1】:

    ih 有 2 个 for 循环,并在内部循环中使用 max_val{i}。这意味着相同的max_val 单元结构将用于h 的每个值——在本例中为size(comb_set,1)=3。对于h 的每次迭代,前一次迭代中定义的max_val{i} 将被覆盖。由于在第一次和第二次运行 size(pairs,1)=3 中,单元格的长度为 3。在最后一个 size(pairs,1)=1 中。单元格的长度仍为 3,但您将只覆盖第一个元素 - 您可以查看您提供的代码的输出,并看到最后两个元素等于前一个 h 迭代的最后两个元素。您需要以不同的方式定义max_val。例如,您可以定义一个数组来保持i 循环中的最大值并将其写入max_values{h}

    当您遇到此类错误时,更容易生成一个最小的工作示例并检查问题所在。这段代码很难阅读,也是因为缺少缩进。 CTRL+A 和 CTRL+I 让你的生活更轻松。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 2018-05-31
      • 2018-10-26
      相关资源
      最近更新 更多