创建一个依赖于另一个月份矩阵的随机日期矩阵
我目前有可变的月份,其中:
months = randi(12,5,1);
这将创建一个 5x1 矩阵,其中包含代表月份的随机数 1-12(1 = 一月,2 = 二月等)
假设一个月只能有 31、30 或 28 天2 月,我如何创建第二个 5x1 矩阵,其中包含在相应月份内发生的随机日期?
举个例子,如果“月份”矩阵中第一个随机生成的数字是 2(代表二月,每月有 28 天),我如何创建第二个 5x1 矩阵,其中所有 5 个随机月份值 1-12 都被分配一个随机值基于相应月份的天数的数字?
我尝试在 for 循环中使用 for 循环来迭代第 2 列中的每个随机数 1-12,并根据该月的最大天数(2 月为 31、30 或 28)生成一个随机日期,但似乎没有去工作。
I currently have the variable months where:
months = randi(12,5,1);
This creates a 5x1 matrix containing random numbers 1-12 which are representative of months (1 = January, 2 = February etc. )
Assuming a month can only have 31, 30 or 28 days in the case of February, how could I create a second 5x1 matrix in which contains a random date in which occurs within it's respective month?
As an example, if the first randomly generated number in the 'months' matrix is 2 (which represents February, with 28 days per month) how could i create a second 5x1 matrix where all 5 random month values 1-12 are assigned a random number based on the amount of days in it's respective month?
I have tried using a for loop inside a for loop to iterate down each random number 1-12 in column 2 and generate a random date based on it's maximum days in such month (31, 30 or 28 for Feb) but it does not seem to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
旁白:我选择避免使用
months
作为变量名称,因为它是内置函数的名称。首先值得注意的是,您可以使用
eomday
获取给定月份的天数。它需要一年(因为 2 月可能会有所不同),但如果您想始终假设 2 月有 28 天,您可以选择一个正确的年份,例如 2022 年。您可以使用它来获取随机月份的最大天数
然后为每个随机月份生成 1 到 maxd 之间的随机整数,
我使用 ceil 向远离 0 的方向舍入,并与 rand 一起生成整数天而不是randi 无法接受我们需要的最大值数组。
因此,一旦您拥有月份数组(
m
),单行解决方案将是如果您出于某种原因(可能是性能)想避免
eomday
,那么您可以定义< code>maxd=eomday(2022,1:12) 并使用m
对其进行索引应该以大致相同的方式工作。Aside: I'm choosing to avoid
months
as a variable name because it is the name of an in-built function.First it's worth noting you can use
eomday
to get the number of days in a given month. It requires a year (since February can vary), but if you want to always assume Feb has 28 days you can just pick a year where that is true, like 2022.You can use this to get the maximum day number for your random months
Then generate random integers between 1 and
maxd
for each random monthI'm using
ceil
to round up away from 0, together withrand
to generate integer days instead ofrandi
which can't accept the array of max values we need.So a one-line solution once you have your array of months (
m
) would beIf you wanted to avoid
eomday
for some reason (performance maybe) then you could definemaxd=eomday(2022,1:12)
and indexing into it usingm
should work in much the same way.