Interesting. While I don't (yet) have a solution for you (solution at bottom), I have a few notes and pointers:
1. The out of memory error is because you're creating a 512*256 by 512*256 element temporary matrix on the right hand side (a(b(:),c(:))+1
). That is 2^34 bytes — 17GB! So that's why you're getting an out of memory error. Note, too, that this array isn't even what you want! Look at this example:
>> a = magic(5);
>> b = [1 5 4]; % The rows that contain the numbers 1,2,3 respectively
>> c = [3 4 5]; % The columns that contain ^ ...
Now, a(1,3) == 1, a(5,4) == 2, etc. But when you say a(b,c)
, you're selecting rows (1,5,4) and columns (3,4,5) for every one of those rows!
>> a(b,c)
ans =
1 8 15
25 2 9
19 21 3
All you care about is the diagonal. The solution is to use sub2ind to convert your subscript pairs to a linear index.
>> a(sub2ind(size(a),b,c))
ans =
1 2 3
2. Your proposed solution doesn't do what you want it to, either. Since Matlab lacks an increment operator, you are simply incrementing all indices that exist in (b,c) by one. And no more. It'll take some creative thinking to vectorize this. Use a smaller array to see what's going on:
>> a = zeros(4,4);
>> b = ones(8,4);
>> c = ones(8,4);
>> a(b,c) = a(b,c) + 1;
>> a
a =
1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Edit Here we go! Vectorized incrementation:
>> idxs = sub2ind(size(a),b(:),c(:)); % convert subscripts to linear indices
>> [unique_idxs,~,ic] = unique(idxs); % Get the unique indices and their locations
>> increment_counts = histc(ic,1:max(ic)); % Get the number of occurrences of each idx
>> a(unique_idxs) = a(unique_idxs) + increment_counts;