MATLAB: How to convert a 2D array x and y to a limited number of pixels

pixel

I am working on a virtual camera model that takes an image of a scene. I have the x and y of the image of each point on the image plain. My problem is that the image should be 640×640 and the scene consists of 12 milion points so there are multiple points in one pixel of image. In the project it is ok to over write the color of the points projected on one pixel so I wrote the following code: (Prime_CO is a 12000000×2 matrix and each row of it has the x a y of each point of the image.RGB_final is a 12000000×3 matrix which has the RGB colors of each point of Prime_CO, the final image should be a 640x640x3 array which has the RGB of each pixel.)
IM1=zeros(640,640,3);
pixel_size=0.01984375;
start_point=-6.35;
for j=1:640
for i=1:640
for num=1:12000000
if Prime_CO(num,1)>=start_point+((j-1)*pixel_size) && Prime_CO(num,1)<=start_point+(j*pixel_size) && Prime_CO(num,2)>=start_point+((i-1)*pixel_size) && Prime_CO(num,2)<=start_point+(i*pixel_size)
IM1(i,j,1)=RGB_final(num,1);
IM1(i,j,2)=RGB_final(num,2);
IM1(i,j,3)=RGB_final(num,3);
end
end
end
end
The problem is that it takes MATLAB a long time to run this code. How should I do this appropriately?

Best Answer

nested for-loop runs slowly. The following is a faster way.
%% data preparation
IM1=zeros(640,640,3);
pixel_size=0.01984375;
start_point=-6.35;
point_num = 12000000;
Prime_CO = (rand(12000000,2) - 0.5) * (-start_point * 2); % simulation of Prime_CO (-6.35 to +6.35)
RGB_final = randi(256,point_num,3) - 1; % simulation of RGB_final (0 - 255)
IM1_1 = zeros(640, 640); % R channel
IM1_2 = zeros(640, 640); % G channel
IM1_3 = zeros(640, 640); % B channel
%% main
Prime_CO_IJ = floor((Prime_CO - start_point) / pixel_size) + 1; % convert point location to row/col indices of IM1.
ind = sub2ind([640,640], Prime_CO_IJ(:,2), Prime_CO_IJ(:,1)); % convert row/col indices to linear indices.
% storing the data
IM1_1(ind) = RGB_final(:,1);
IM1_2(ind) = RGB_final(:,2);
IM1_3(ind) = RGB_final(:,3);
% image matrix generation
IM1 = uint8(cat(3, IM1_1, IM1_2, IM1_3)); % 640x640x3
hope this helps.