简体   繁体   English

在Matlab中有效访问矩阵中的元素

[英]Efficient Access of elements in Matrix in Matlab

I have an mxn matrix of integers and where n is a fairly big number m and n ~1000. 我有一个整数的mxn矩阵,其中n是一个相当大的数m,n约为1000。 I want to iterate through all of these and perform a some operations, like accessing a particular cell and assigning a value of a particular cells. 我想遍历所有这些并执行一些操作,例如访问特定的单元格并分配特定单元格的值。

However, at least in my implementation, this is rather inefficient as I have two for loops with Matrix(a,b) = Matrix(a,b+1) or something along these lines. 但是,至少在我的实现中,这效率很低,因为我有两个for循环,其中Matrix(a,b)= Matrix(a,b + 1)或类似的东西。 Is there any other way to do this seeing as my current implementation takes a long time to traverse through about 100,000 cells and perform some operations. 还有其他方法可以做到这一点,因为我当前的实现需要很长时间才能遍历大约100,000个单元并执行一些操作。

Thank you 谢谢

In matlab, it's almost always possible to avoid loops. 在matlab中,几乎总是可以避免循环。 If you want to do Matrix(a,b)=Matrix(a,b+1) , you should just do Matrix2=Matrix(:,2:end); 如果要执行Matrix(a,b)=Matrix(a,b+1) ,则应该只执行Matrix2=Matrix(:,2:end);

If you are more precise about what you do inside the loop, I can help you more. 如果您对循环内的操作更为精确,我可以为您提供更多帮助。

Matlab uses column major ordering of matrixes in memory (unlike C). Matlab使用内存中矩阵的列主排序(与C不同)。 Are you sure you are iterating the indexes in the correct order? 您确定要以正确的顺序迭代索引吗? If not, try switching them and see if performance improves.. 如果不是,请尝试切换它们,看看性能是否得到改善。

如果您无法摆脱for循环,则一种可能是用C重写昂贵的操作并按此处所述创建MEX文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM