Is there a better way to do this for-loop?
for i = find(A > 42)
B(A(i), i) = B(A(i), i) + 1;
end
A is an integer array. B is a max(A)×length(A) matrix.
Example:
A = reshape(magic(3), 1, 9); %# 8 3 4 1 5 9 6 7 2
B = zeros(max(A), length(A));
for i = find(A > 3)
B(A(i), i) = B(A(i), i) + 1;
end
B = [
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
]
I’d recommend linear indexing for this case. Convert your row/column subindices into linear indices with sub2ind.
You can combine this into a one-liner if you want, I left it as multiple lines for clarity.