创建一个矩阵,其中A(i,j)= i * j [英] Create a matrix with A(i, j) = i*j

查看:246
本文介绍了创建一个矩阵,其中A(i,j)= i * j的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习科迪问题:

我们有时不得不记住无聊的时间表. 5乘5等于25.5乘6等于30.12乘12远远超出您的想象.

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.

使用MATLAB,时间表应该很容易!编写一个输出时间表的函数,该表可以达到要求的大小.

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

我用下面的代码解决了.

I solved it with the code below.

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

我可以在没有for个周期的情况下编写它并提高得分吗?

Could I write it without for cycles and improve my score?

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

It may look stupid, but it is also useful for my work.

推荐答案

使用 ndgrid 这是一个简单的任务.

With ndgrid it's an easy task.

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

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

Alternatively use bsxfun, probably fastest solution, as bsxfun is always the fastest ;):

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

这篇关于创建一个矩阵,其中A(i,j)= i * j的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆