Info

This question is closed. Reopen it to edit or answer.

How I can vectorize the next code?

1 view (last 30 days)
Alfredo Rojas
Alfredo Rojas on 1 Oct 2012
Closed: MATLAB Answer Bot on 20 Aug 2021
Hello. M is a matrix and v and w are vectors of the same length containing some indices of M. I want to vectorize the following code (without using loops)
for i=1:length(v);
M(v(i),w(i)) = 1;
end

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 1 Oct 2012
Edited: Azzi Abdelmalek on 1 Oct 2012
M=magic(5); % example
v=1:2;
w=3:4
idx=sub2ind(size(M),v,w)
M(idx)=1

Image Analyst
Image Analyst on 1 Oct 2012
You simply do
M(v, w) = 1;
Here's proof:
M = magic(10)
v = randi(10, 5,1)
w = randi(10, 5,1)
M(v,w) = 1
  2 Comments
Alfredo Rojas
Alfredo Rojas on 1 Oct 2012
This code assigns 1 to each combinations of indices on v and w
Image Analyst
Image Analyst on 1 Oct 2012
Edited: Image Analyst on 1 Oct 2012
Ah, you're right, that won't work (though it seems like it would). Use Azzi's code then.

Andrei Bobrov
Andrei Bobrov on 1 Oct 2012
Edited: Andrei Bobrov on 1 Oct 2012
M = randi([100,300],10);
v = randi(10,7,1);
w = randi(10,7,1);
M(v + size(M,1)*(w-1)) = 1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!