0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If r and v are the same length, then r(1:length(v)) simplifies to just r.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.