Help vectorize my poor code or make it faster

조회 수: 1 (최근 30일)
Charles
Charles 2011년 3월 9일
I have an N X 4 dimensional data with information of x,y,z coordinates and Intensity values of a 3D image. I need to reconstruct this data slice by slice and have written a code which does this, however, it is VERY slow due to the for-loops I used. Could anyone suggest how I can vectorize this code, I think my brain is getting slower :-(. Here is my code:
[x, y, z, int] = textread('data.txt','%d%d%d%f'); %read in data
mat = zeros(300, 300); %define the image matrix
slice_num = 0; % select the slice to reconstruct
ind1 = find(x == slice_num);
z1 = z(ind1); y1 = y(ind1); x1 = x(ind1); int1 = int(ind1); %Extract only data relevant to the slice
for i = 1 : 300; %Column of image matrix
for j = 1 : 300; %row of image matrix
for k = 1: length(z1);
ind = find(z1(k) == i && y1(k) == j);
if (ind>0);
mat(i,j) = int1(k);
else
end
end
end
end
So there you have it, make my day :-)
Regards, Charles
  댓글 수: 1
Jan
Jan 2011년 3월 9일
What do you want to achive by "ind = find(z1(k) == i && y1(k) == j); if (ind>0)"? FIND does never reply anything <= 0.

댓글을 달려면 로그인하십시오.

채택된 답변

Richard
Richard 2011년 3월 9일
If your y and z values are all integers then I think this will work in place of the nested for loops:
idx = sub2ind(size(mat), z1, y1);
mat(idx) = int1;
If that is not the case then you need to do an additional pre-process step to filter out non-integer (y1,z1) pairs:
isInt = (y1==fix(y1)) & (z1==fix(z1));
idx = sub2ind(size(mat), z1(isInt), y1(isInt));
mat(idx) = int1(isInt);
  댓글 수: 1
Charles
Charles 2011년 3월 9일
I expected a speed up to my code, man, u made it supersonic :-). Thanks for the help, really made my day.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2011년 3월 9일
Although I think your whole loop can be easily vectorized as Richard has alluded to, I think a simple speed up would be to run the k-for-loop backwards. You only keep the final working solution (mat(i,j)=last_working_value), so you might as well start at the end and break the for-loop when your criteria is met.
Sample data would make this problem much easier for us as well.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by