在 MATLAB 中一般导入上三角矩阵
我一直在尝试进行一般导入 Ghaul 对我之前的问题的回答关于导入上三角矩阵。
初始数据:
1.0 3.32 -7.23
1.00 0.60
1.00
A = importdata('A.txt')
A =
1.0000 3.3200 -7.2300
1.0000 0.6000 NaN
1.0000 NaN NaN
因此,您必须像这样移动最后两行:
A(2,:) = circshift(A(2,:),[0 1])
A(3,:) = circshift(A(3,:),[0 2])
A =
1.0000 3.3200 -7.2300
NaN 1.0000 0.6000
NaN NaN 1.0000
然后将 NaN 替换为其对称对应项:
A(isnan(A)) = A(isnan(A)')
A =
1.0000 3.3200 -7.2300
3.3200 1.0000 0.6000
-7.2300 0.6000 1.0000
我有这个,因此我们可以获得任何大小的完整矩阵:
A = importdata('A.txt')
for i = (1:size(A)-1)
A(i+1,:) = circshift(A(i+1,:),[0 i]);
end
A(isnan(A)) = A(isnan(A)');
这种方法是最好的吗?一定有更好的东西。我记得有人告诉我尽量不要在 MATLAB 中使用 for
循环。
更新
所以这就是结果。有什么方法可以在不使用循环的情况下使其更快吗?
A = importdata('A.txt')
for i = (1:size(A)-1)
A(i+1,:) = circshift(A(i+1,:),[0 i])
end
A(isnan(A)) = 0;
A = A + triu(A, 1)';
I have been trying to make a general import of Ghaul's answer to my earlier question about importing an upper triangular matrix.
Initial Data:
1.0 3.32 -7.23
1.00 0.60
1.00
A = importdata('A.txt')
A =
1.0000 3.3200 -7.2300
1.0000 0.6000 NaN
1.0000 NaN NaN
So you will have to shift the two last rows, like this:
A(2,:) = circshift(A(2,:),[0 1])
A(3,:) = circshift(A(3,:),[0 2])
A =
1.0000 3.3200 -7.2300
NaN 1.0000 0.6000
NaN NaN 1.0000
and then replace the NaNs with their symmetric counterparts:
A(isnan(A)) = A(isnan(A)')
A =
1.0000 3.3200 -7.2300
3.3200 1.0000 0.6000
-7.2300 0.6000 1.0000
I have this, so we get the complete matrix for any size:
A = importdata('A.txt')
for i = (1:size(A)-1)
A(i+1,:) = circshift(A(i+1,:),[0 i]);
end
A(isnan(A)) = A(isnan(A)');
Is this approach the best? There must be something better. I remember someone told me to try not to use for
loops in MATLAB.
UPDATE
So this is the result. Is there any way to make it faster without the loop?
A = importdata('A.txt')
for i = (1:size(A)-1)
A(i+1,:) = circshift(A(i+1,:),[0 i])
end
A(isnan(A)) = 0;
A = A + triu(A, 1)';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是另一个适用于任何大小的上三角矩阵的通用解决方案。它使用函数 ROT90、SPDIAGS 和 TRIU:
Here's another general solution that should work for any size upper triangular matrix. It uses the functions ROT90, SPDIAGS, and TRIU:
这是一种没有循环的方法。如果您有更新版本的 Matlab,您可能需要检查哪个解决方案确实更快,因为循环并不像以前那么糟糕。
Here's one way without loop. If you have a more recent version of Matlab, you may want to check which solution is really faster, since loops aren't as bad as they used to be.