Help vectorize my poor code or make it faster
1 次查看(过去 30 天)
显示 更早的评论
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
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
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 个)
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!