Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Can anyone help me improve this code?

조회 수: 1 (최근 30일)
dave
dave 2013년 5월 29일
마감: MATLAB Answer Bot 2021년 8월 20일
I'm working on a function which takes an n-by-1 array (called "ts") as input and creates a n-by-n matrix (called "V"), where each element of V is either 0 or 1.
Now imagine "ts" as a plot: If one can connect an arbitrary point (e.g. ts(5)) with another arbitrary point (e.g. ts(47)) using a straight line without intersecting the time series, then the matrix elements V(5,47) and V(47,5) should be 1. If the two points can't be connected without intersecting the time series then the corresponding elements in the matrix should be 0. This is supposed to be done for all possible pairs of points in "ts".
Here's my code: It works, but it's very inefficient (especially because of the three nested loops). Any idea on how to improve the code would be much appreciated...
function V = someFunction(ts)
len = length(ts);
V = zeros(len, len);
for a = 1:len,
for b = 1:len,
intersection = [];
for c = min(a,b)+1 : max(a,b)-1,
t_a = a;
y_a = ts(a);
t_b = b;
y_b = ts(b);
t_c = c;
y_c = ts(c);
if (y_c < y_b + (y_a - y_b) * ((t_b - t_c) / (t_b - t_a))),
intersection = [intersection; 0];
else
intersection = [intersection; 1];
end
end
if all(intersection==0),
V(a,b) = 1;
end
end
end
%Set the diagonal to zero.
V(1:len+1:len*len) = 0;
end
EDIT: Small sample of "ts": 74.7900 75.1100 73.3100 72.0100 71.4700 70.8300 68.4800 69.5200 70.0700 68.9800 68.8300
  댓글 수: 4
dave
dave 2013년 5월 29일
편집: dave 2013년 5월 29일
If y(c) is above the line connecting points a and b, then it's considered an intersection. The typical length of "ts" would be between 50 and several tousands.
@Matt Kindig: I'm not quite sure how to provide you with input and output samples on Matlab Answers..
Matt Kindig
Matt Kindig 2013년 5월 29일
Just edit your question to include them (for a small ts vector--maybe 10 samples or so).

답변 (1개)

Iain
Iain 2013년 5월 29일
A few things come to mind.
1. Only do half of the loops as you point out, V = V', so you only need to do one triangle of it.
2. You can use "break" to finish loops quickly - and you can do your check on each loop in c. - Or you could just do that comparison as a vector operation, eg:
c = min(a,b)+1 : max(a,b)-1;
yc = ts(c);
intersection = (y_c < y_b + (y_a - y_b) .* ((t_b - c) / (t_b - t_a)));
3. I think your calc to see if there has been an intersection is wrong, but that could be that you meant something else.
  댓글 수: 1
dave
dave 2013년 5월 31일
편집: dave 2013년 5월 31일
Thanks for the suggestions - I'll implement them. However, any ideas on how to completely vectorize the code would be great.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by