I’m trying to assign ~1 Million values to a 100×100 logical matrix like this:
CC(Labels,LabelsXplusOne) = true;
where CC is 100×100 logical and Labels, LabelsXplusOne are 1024×768 int32.
The problem now is the above statement takes about as long as 5 minutes to complete on a modern CPU.
Obviously it is badly implemented in MATLAB, so how can we make the above run faster without resorting to loops?
In case you are wondering, i need this statement to compute blobs in a integer (not binary) image.
And also:
max(max(Labels)) = 100
max(max(LabelsXplusOne)) = 100
EDIT:
Ok i got it. Maybe this will help others in the future:
tic; CC(sub2ind(size(CC),Labels,LabelsXplusOne)) = true; toc;
Elapsed time is 0.026414 seconds.
Much better now.
There are a couple of issues that jump out at me…
I have the feeling you are doing the matrix indexing wrong. As it stands now, what will happen is every value in
Labelswill be paired with every value inLabelsXplusOne, producing (1024*768)^2 total index pairs for your rows and columns ofCC. That’s likely what’s taking so long.What you probably want is to only use each pair of values as indices, like
Labels(1,1),LabelsXplusOne(1,1),Labels(1,2),LabelsXplusOne(1,2), etc. To do this, you should convert your indices into linear indices using the function SUB2IND.Additionally, your matrix
CConly contains 10,000 entries, yet your index matrices each contain 786,432 integer values. This means you will end up assigning the valuetrueto the same entry inCCmany times over. You should first remove redundant sets of indices using the function UNIQUE, then use them to assign values toCC.This is what I think you want: