问题描述
我有一个矩阵A
,其中包含一年中每一天的24个值(每小时一个值). A
的每一列都是不同的一天,每天都有24行数据(A
是24-by-365).我想通过比较每天的小时数据来相互比较每一天.为此,我获取一列数据并将其与下一列进行比较.我将两列中每个小时的数据之差取平方,然后求和并求和得出一个单一值,该值指示两天的相似程度.然后,我用可能的几天组合进行此操作,创建一个365 x 365矩阵d
,该矩阵表示每一天之间的相似度.例如,元素d(20,100)
包含一个值,该值指示一年中的第20天与第100天有多相似.该代码正在运行,但是速度很慢,我希望能够对其进行向量化.帮助将不胜感激.
I have a matrix A
that contains 24 values for each day of the year (one value for each hour). Each column of A
is a different day and each day has 24 rows worth of data (A
is 24-by-365). I want to compare each day to each other by comparing the hour data of each day. To do this, I take one column of data and compare it to the next column. I take the difference of each hour's data in the two columns and then square and sum them to get a single value indicating how similar the two days are. I then do this with every possible combination of days, creating a 365-by-365 matrix, d
, indicating how similar each day is to each other day. For example, element d(20,100)
contains a value indicating how similar the 20th day of the year is to the 100th. The code is working, but it is quite slow and I would like to be able to vectorize it. Help would be greatly appreciated.
for j=1:365
for k=1:365
d(j,k)=sqrt(sum((A(:,j)-A(:,k)).^2));
end
end
推荐答案
使用 pdist
,它在C语言中起着举足轻重的作用,并且> c6> 创建距离矩阵:
d = squareform(pdist(A.'));
如果您需要更快的速度(虽然365 x 365并不是很大),请在此处或尝试使用此文件交换程序
If you need this to be even faster (365-by-365 is not very big though), see my answer here or try this File Exchange program.
这篇关于在Matlab中向量化double for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!