Help vectorize my poor code or make it faster

1 Ansicht (letzte 30 Tage)
Charles
Charles am 9 Mär. 2011
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 Kommentar
Jan
Jan am 9 Mär. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sean de Wolski
Sean de Wolski am 9 Mär. 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.

Kategorien

Mehr zu Images finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by