Efficient matrix comparisons that retain row/column order
1 次查看(过去 30 天)
显示 更早的评论
Hi Everyone,
I've been struggling to figure out an efficient way to compare matrices and have the results stored in a matrix of a comparable size and similar ordering rather than in a vector of scalars for the case where the comparison is true. Can anyone share with me a faster way of doing this than just using for loops?
For example, suppose we start with:
mat1 = rand(10,10);
mat2 = rand(10,10);
difr = mat1 - mat2;
What I want to do is create a new matrix called mat3 (that is of the same dimensions as mat1 and mat2) where each element mat3(i,j) = mat1(i,j) if difr < 0.2 but 0 otherwise.
To do this, I make my best guess and try using the following code (whch I know is incorrect):
mat3 = zeros(10,10);
mat3 = mat1(diff < 0.2)
This turns mat3 into an Nx1 matrix where N is the number of times that the comparison is true ... and all of the information about position (e.g. i,j) in the original mat1 matrix is lost.
Can anyone share the proper way of doing this?
Thank you,
R
0 个评论
采纳的回答
per isakson
2012-5-26
This would be my first trial:
mat3 = mat1;
mat3( diff >= 0.2 ) = 0;
This isn't magic it is logical indexing!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!