Matlab大型方阵循环向量化优化求助:替换耗时for循环
Hey there! That loop is definitely going to be a massive bottleneck for a large matrix like your 500k-element refConnect—let's replace it with a clean, lightning-fast vectorized approach that leverages MATLAB's optimized matrix operations.
The Issue with Your Original Code
Your current implementation:
tmp = find(referenceCluster == 67); for j=1:length(tmp) refConnect(tmp(j),tmp)=1; end
does exactly what you intend: sets every element in row tmp(j) and columns tmp to 1, one row at a time. But looping through each row individually adds huge overhead, especially when tmp is a large index set.
The Simple Vectorized Fix
You can get the exact same result in one line (after retrieving tmp), no loops required:
tmp = find(referenceCluster == 67); refConnect(tmp, tmp) = 1;
MATLAB supports direct subset indexing for matrices—this line targets all rows in tmp and all columns in tmp simultaneously, setting every intersection of those rows and columns to 1 in a single optimized operation.
Why This Is So Much Faster
MATLAB’s core is built around optimized low-level matrix operations (often leveraging BLAS/LAPACK libraries). Vectorized indexing skips the per-iteration overhead of a for loop and handles the entire block assignment in one go. For a matrix of your size, this will cut runtime from potentially minutes down to milliseconds.
Quick Verification Example
Suppose referenceCluster = [1, 67, 3, 67], so tmp = [2, 4]. Running refConnect(tmp, tmp) = 1 will set elements (2,2), (2,4), (4,2), (4,4) all to 1—exactly what your original loop would do, but in a single step.
内容的提问来源于stack exchange,提问作者oldflatop

