MATLAB Answers

How do I get a loop to calculate for each value of a formula, not just the last n of the input(N)?

조회 수: 4(최근 30일)
David Prendergast
David Prendergast 2020년 11월 23일
댓글: Rik 2020년 11월 23일
Take a table T, where the columns are x and y coordinates, and each row represents a point. The length is calculated from the first two values, i.e (1,2) for each N.
Whenever I run this, it goes through the iteration for length, but it only uses length at j=5 to calculate force.
My question is how do I get the loop to calculate length, put that through the force formula, and then add to the force sum, then repeat for next iteration?
T = [1 2 ; 3 4 ; 5 6 ; 7 8 ; 9 10];
N=5;
force=0;
length=0;
for F = 1:(N-1)
for j=(F+1):N
length = sqrt((T(j,1)-T(1,1))^2+(T(j,2)-T(1,2))^2);
force = force + 2.2*((10/length)^3-(10/length)^2);
end
end
disp(force)
  댓글 수: 1
Rik
Rik 2020년 11월 23일
Why did you try to delete your question? That is a very rude thing to do. If you want private consulting, hire a consultant. I have restored your edit from the Google cache, which unforturnately didn't contain the comments you posted.
Don't be a jerk. Leave your question as it is now so other people can benefit from the question and the answer.

댓글을 달려면 로그인하십시오.

채택된 답변

Jon
Jon 2020년 11월 23일
편집: Jon 2020년 11월 23일
You must provide an array to hold your output force. You keep overwriting it with each loop iteration
So, depending upon what you want
F(i,j) = ...
or
F(i) = ...
  댓글 수: 3
Jon
Jon 2020년 11월 23일
Sorry, I didn't notice on my first look that you had force on the right hand side of the equation also.
If you could please further explain, what you are trying to calculate (maybe with an example of what you are expecting for a result for a particular case) I might be able to help further. I'm not clear now what might just be errors in how you are coding it and what are things your are really trying to do.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

VBBV
VBBV 2020년 11월 23일
편집: VBBV 2020년 11월 23일
%if true
for j=1:N
You need to use above loop structure. You don't need one for loop

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by