I have a vector v of values and a vector r of indices. I want to store the values in a matrix m as follows:
for i = 1:length(v)
m(i, r(i)) = v(i);
end
What is the fastest way to do this in a vectorized way?
I do not know if it is faster, I suppose so but the difference might be very small, but here is one way:
m(sub2ind(size(m),1:length(v),r(1:length(v))))=v;
If r is a column vector then sub2ind will complain about vectors size, you can just take its transpose and it will solve this.
r and v are the same length, then r(1:length(v)) simplifies to just r.