有没有一种方便的方法可以多次调用一个函数而无需循环?

发布于 2025-01-19 19:44:40 字数 574 浏览 0 评论 0原文

我目前正在制作一些代码,以随机生成一组随机日期并将其分配给矩阵。我希望随机生成n个量的日期(天和月),并将其显示在NX2矩阵中。我的代码如下如下,

function dates = dategen(N)

    month = randi(12);

    if ismember(month,[1 3 5 7 8 10 12])
        day = randi(31);
        dates = [day, month];
    elseif ismember(month,[4 6 9 11])
        day = randi(30);
        dates = [day, month];
    else
        day = randi(28);
        dates = [day, month];
    end

end

例如,如果我打电话给该函数,正如

output = dategen(3)

我期望的2x3矩阵中的3个日期一样。但是,我不确定该怎么做。我相信我需要将n包括在某个地方的功能中,但我不确定在哪里或如何。 任何帮助将不胜感激。

I am currently making some code to randomly generate a set of random dates and assigning them to a matrix. I wish to randomly generate N amount of dates (days and months) and display them in a Nx2 matrix. My code is as follows

function dates = dategen(N)

    month = randi(12);

    if ismember(month,[1 3 5 7 8 10 12])
        day = randi(31);
        dates = [day, month];
    elseif ismember(month,[4 6 9 11])
        day = randi(30);
        dates = [day, month];
    else
        day = randi(28);
        dates = [day, month];
    end

end

For example if I called on the function, as

output = dategen(3)

I would expect 3 dates in a 2x3 matrix. However, I am unsure how to do this. I believe I need to include N into the function somewhere but I'm not sure where or how.
Any help is greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

俯瞰星空 2025-01-26 19:44:40

您可以使用逻辑索引来完成此操作,如下所示:

function dates = dategen(N)

months = randi(12, 1, N);

days = NaN(size(months)); % preallocate
ind = ismember(months, [1 3 5 7 8 10 12]);
days(ind) = randi(31, 1, sum(ind));
ind = ismember(months, [4 6 9 11]);
days(ind) = randi(30, 1, sum(ind));
ind = ismember(months, 2);
days(ind) = randi(28, 1, sum(ind));

dates = [months; days];

end

You can do it using logical indexing as follows:

function dates = dategen(N)

months = randi(12, 1, N);

days = NaN(size(months)); % preallocate
ind = ismember(months, [1 3 5 7 8 10 12]);
days(ind) = randi(31, 1, sum(ind));
ind = ismember(months, [4 6 9 11]);
days(ind) = randi(30, 1, sum(ind));
ind = ismember(months, 2);
days(ind) = randi(28, 1, sum(ind));

dates = [months; days];

end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文