gpt4 book ai didi

Matlab:将年份合并为区间

转载 作者:行者123 更新时间:2023-12-03 21:38:06 24 4
gpt4 key购买 nike

我有一个带有几十年的向量(请注意,有些几十年是故意遗漏的:

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 的评论):

一个。每 十年 不会超过一个

decadeyears 始终排序。

代码

%// 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

关于Matlab:将年份合并为区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com