从包含每个可能对的最大值的向量构建一个矩阵
给定一个大小为 n 的向量,
A=[2 2 5 1] % n=4
构建一个大小为 nxn 的矩阵 R,其中与元素 (i,j) 对应的值是 A(i) 和 A(j) 之间的最大值,
R =
2 2 5 2
2 2 5 2
5 5 5 5
2 2 5 1
我使用 for 循环来执行此操作。有更有效的方法吗?
R = zeros(size(a,2))
for i=1:size(R,1)
for j=1:size(R,2)
R(i,j) = max(A(i),A(j));
end
end
感谢您的帮助 :)
Given a vector of size n
A=[2 2 5 1] % n=4
Build a matrix R of size nxn in which the value correspondent to the element (i,j) is the maximum between A(i) and A(j)
R =
2 2 5 2
2 2 5 2
5 5 5 5
2 2 5 1
I am doing this with a for loop. Is there a more efficient way?
R = zeros(size(a,2))
for i=1:size(R,1)
for j=1:size(R,2)
R(i,j) = max(A(i),A(j));
end
end
Thanks for your help :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这至少是一种更Matlaby的方式:
我希望它会快得多。
This is at least a more matlaby way:
I would expect it's a lot faster.
嗯,说实话,真正的 MATLAB 方法并不是 Johan 所建议的那样。这甚至不是最快的方法。使用 bsxfun 的速度要快三倍,以真正的 MATLAB 方式。
Well, to be honest, the true MATLAB way is not what Johan has suggested. It is not even the fastest way. Three times faster is to use bsxfun, in the true MATLAB way.
这是一个扩展的评论,而不是一个答案......我失去了与开发服务器的连接,所以认为浪费一些时间是合适的。我定义了一个包含以下代码的脚本文件:
另一个脚本包含:
以及第三个脚本包含:
并各运行 5 次。平均 tElapseds 为:1.7674s、0.0520s、0.0645s,因此 @Johan Lundberg 的答案赢得了(时间)效率的桂冠。
为了完整起见,我计时了@woodchips 的回答;平均经过时间为 0.0206 秒。 @Johan 因荣誉被夺走而蒙受耻辱。
This is an extended comment, not an answer ... I've lost connectivity to my development servers, so thought it appropriate to waste some time. I defined a script file containing the code:
another script containing:
and a third containing:
and ran them each 5 times. The mean tElapseds were: 1.7674s, 0.0520s, 0.0645s, so @Johan Lundberg's answer takes the laurels for (time) efficiency.
For the sake of completeness, I timed @woodchips answer; mean time elapsed was 0.0206s. @Johan suffers the ignominy of having the laurels snatched from his brow.
所以我建议你只检查一次:(
保存你的尺寸(A,2),因为它在输入后不会改变,否则matlab每次都会计算它!)
So I suggest you check only once:
(save your size(A,2) since it won't change after input and otherwise matlab will compute it every time!)