Hello All, I try to optimize the following code. I have this example fib_dist_ang matrix. First column numbers are not relevant to discussion. second column values are sorted while third column are not sorted.
I wanted to sort the third column values. This sorting is based on same value in the second column and place the value closest to the theta_ran (e.g. theta_ran =7.0) value. During this sorting based on the third row, In this example, lets confine discussion to last three rows we have to change the all values in the row (like how SORTROWS() command does). Output I requested is as follows:
Notes: 1) I had used UNIQUE to find the first and last rows of the repetitions based on the second column value. 2) To find the closest value, I had used histc.
fib_dist_ang=%required output
2 0.008 5.2
22 0.008 6.2
42 0.014 4.7
43 0.016 7.2
3 0.016 2.2
23 0.016 6.7
fib_dist_ang= %input
22 0.008 6.2
2 0.008 5.2
42 0.014 4.7
23 0.016 6.7
43 0.016 7.2
3 0.016 2.2
[~,uniq_first,~] = unique(fib_dist_ang(:,2), 'first');
[~,uniq_last,~] = unique(fib_dist_ang(:,2), 'last');
tic_sortang=tic;
for i2=1:size(uniq_first,1)
ithrow=sortrows(fib_dist_ang(uniq_first(i2):uniq_last(i2),:),3);
val=theta_ran; f=ithrow(:,3);
if val > f(1) && val < f(end)
[N,bin]=histc(val,f);
index=bin+1;
if abs(val-f(bin))<abs(val-f(bin+1))
fclosest=f(bin); index=bin;
else
fclosest=f(index);
end
ithrow=[ithrow(index,:);ithrow(1:index-1,:);ithrow(index+1:end,:) ];
end
fib_dist_ang(uniq_first(i2):uniq_last(i2),:)=ithrow;
end
Only this loop is taking almost half of my total program time. Hence, I am looking for any possibility to optimize this program.
4 Comments
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344232
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344232
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344236
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344236
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344237
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344237
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344238
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/269183-sorting-sub-matrices-based-on-specific-column-value#comment_344238
Sign in to comment.