1

I have an array of velocity and I want to get an array of displacement. To get displacement for each n,i need add speed[] from 0 to n, So I'm trying to add first n numbers for each n in array speed[],n is the index of array start from 0.

for (i = 0; i < totalnumber; i++)
{
    for (int k = 0; k < i; k++)
    {
        Xdis[i] += Xvelo[k];
        Ydis[i] += Yvelo[k];
        Zdis[i] += Zvelo[k];
    }
 }

the loop above works,but the problem is it takes too long(loop in loop) my question is, is there any sum function in C# can handle this without use for loop? like Xdis[i]=Xvelo.sum(i) or sth?

5
  • 1
    I don't think you will get this optimized more then the way you already did. What are is the value for totalnumber? Commented Jun 2, 2014 at 8:20
  • 1
    And is there any reason you want to have three separate arrays rather than one array of 3D vectors? (Always treat "multiple collections which are related by index" with suspicion, and consider having a single collection of a composite type instead.) Commented Jun 2, 2014 at 8:21
  • Linq may help you make this more readable but it's not going to make it more efficient. It will still do the same calculations (if you're lucky) under the covers. Commented Jun 2, 2014 at 8:24
  • totalnumber is 4096,this for loop can hang my program for around 1 sec. Commented Jun 2, 2014 at 8:27
  • @JonSkeet Yes I'll need to display those points with zedgraph later.I'll try learn 3D vector array also,tq! Commented Jun 2, 2014 at 8:34

1 Answer 1

4

Why don't you use the results you already calculated? Instead of re-summing all the way up, just use the previous result:

for (i = 1; i < totalnumber; i++)
{
    Xdis[i] = XDis[i-1] + Xvelo[i-1];
    Ydis[i] = YDis[i-1] + Yvelo[i-1];
    Zdis[i] = ZDis[i-1] + Zvelo[i-1]; 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.