How I can vectorize the next code?
情報
この質問は閉じられています。 編集または回答するには再度開いてください。
古いコメントを表示
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
0 件のコメント
回答 (3 件)
Azzi Abdelmalek
2012 年 10 月 1 日
編集済み: Azzi Abdelmalek
2012 年 10 月 1 日
M=magic(5); % example
v=1:2;
w=3:4
idx=sub2ind(size(M),v,w)
M(idx)=1
0 件のコメント
Image Analyst
2012 年 10 月 1 日
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 件のコメント
Alfredo Rojas
2012 年 10 月 1 日
Image Analyst
2012 年 10 月 1 日
編集済み: Image Analyst
2012 年 10 月 1 日
Ah, you're right, that won't work (though it seems like it would). Use Azzi's code then.
Andrei Bobrov
2012 年 10 月 1 日
編集済み: Andrei Bobrov
2012 年 10 月 1 日
M = randi([100,300],10);
v = randi(10,7,1);
w = randi(10,7,1);
M(v + size(M,1)*(w-1)) = 1
0 件のコメント
この質問は閉じられています。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!