gpt4 book ai didi

matlab - 创建一个矩阵 A(i, j) = i*j

转载 作者:行者123 更新时间:2023-12-02 05:33:03 25 4
gpt4 key购买 nike

我在练习一个 Cody 问题:

At one time or another, we all had to memorize boring times tables. 5 times 5 is 25. 5 times 6 is 30. 12 times 12 is way more than you think.

With MATLAB, times tables should be easy! Write a function that outputs times tables up to the size requested.

我用下面的代码解决了它。

function m = timestables(n)
for i =1:n
for j = 1:n
m(i,j) = i*j;
end
end
end

我可以在没有 for 循环的情况下编写它并提高我的分数吗?

它可能看起来很愚蠢,但它对我的工作也很有用。

最佳答案

ndgrid这是一项简单的任务。

[x,y] = ndgrid(1:n)
m = x.*y

或者使用 bsxfun ,可能是最快的解决方案,因为 bsxfun 总是最快的 ;):

m = bsxfun(@times,1:n,(1:n).')

关于matlab - 创建一个矩阵 A(i, j) = i*j,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29343172/

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