2017-06-01 92 views
0

如何矢量化下面的代碼?如何矢量化這個for循環

這裏x_cordsy_cords都是7894 * 1向量和buffImg是一個虛擬零圖像,我試圖映射線和得到一個細分圖像。

for i = 1:length(x_cords) 
    buffImg(y_cords(i),x_cords(i)) = 1; 
end 

回答

2

在這種情況下,你需要變換存儲在x_cordsy_cords到使用sub2ind -function線性指標的下標索引,然後您可以直接分配像這樣的:

buffImg=zeros(100,100); 
x=randperm(100); 
y=randperm(100); 
buffImg(sub2ind(size(buffImg),x,y))=1; 

只是爲了告訴你,輸出是一樣的,這裏是你如何測試它:

x=randperm(100); 
y=randperm(100); 
buffImg=zeros(100,100); 
buffImg2=zeros(100,100); 
for i = 1:length(x) 
    buffImg(x(i),y(i)) = 1; 
end 
buffImg2(sub2ind(size(buffImg),x,y))=1; 
all(all(buffImg==buffImg2)) 
+0

輸出是不符合預期,buffImg的大小是3328 * 2560,如果它是有用的,所以總共8519680像素,其中7894線必須作出 – Gopi

+0

我試過你的代碼和我的代碼,它有完全相同的輸出。你確定,你沒有做錯什麼?我添加了一些代碼來向你展示你的輸出和我的等價。 – Max

+0

哎呀對不起,我明白了,你用了x_cords,y_cords而不是y_cords,x_cords。 – Gopi