Help vectorize my poor code or make it faster

3 views (last 30 days)
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 Comment
Jan
Jan on 9 Mar 2011
What do you want to achive by "ind = find(z1(k) == i && y1(k) == j); if (ind>0)"? FIND does never reply anything <= 0.

Sign in to comment.

Accepted Answer

Richard
Richard on 9 Mar 2011
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 Comment
Charles
Charles on 9 Mar 2011
I expected a speed up to my code, man, u made it supersonic :-). Thanks for the help, really made my day.

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 9 Mar 2011
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.

Categories

Find more on Images in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!