我有一个数十年的向量(请注意,故意遗漏了几十年:
decades = [1910 1920; 1921 1930; 1931 1940; 1951 1960]
以及具有几年信息(每十年最多1个)的向量,其中包含一条信息(假设是事故):
years = [1916 35; 1923 77; 1939 28; 1941 40; 1951 32]
除了使用循环之外,是否有其他方法可以将信息组合到几十年?
result = [1910 1920 35; 1921 1930 77; 1931 1940 28; 1951 1960 32]
最佳答案
假设(摘自OP的评论):
一个。每个year
最多只能包含一个decade
。
b。 decade
和years
始终进行排序。
码
%// Slightly different inputs to verify the correctness of code across
%//general cases, but within the above mentioned assumptions
decades = [1910 1920; 1921 1930; 1931 1940; 1951 1960; 1971 1980]
years = [1916 35; 1939 28; 1941 40; 1951 32]
cm = bsxfun(@ge,years(:,1),decades(:,1)') & bsxfun(@le,years(:,1),decades(:,2)')
select_years = any(cm,2)
select_decades = any(cm,1)
%// If result is needed such that decades which do not have a entry in
%// years must be logged in with the third column as 0
result = [decades sum(bsxfun(@times,cm,years(:,2)))'] %//'
%// If result is needed such that decades which do not have a entry in
%// years must be skipped
result = [decades(select_decades,:) years(select_years,2)]
输出量
decades =
1910 1920
1921 1930
1931 1940
1951 1960
1971 1980
years =
1916 35
1939 28
1941 40
1951 32
result =
1910 1920 35
1921 1930 0
1931 1940 28
1951 1960 32
1971 1980 0
result =
1910 1920 35
1931 1940 28
1951 1960 32