4 views (last 30 days)

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)

Jon
on 23 Nov 2020

Edited: Jon
on 23 Nov 2020

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) = ...

Jon
on 23 Nov 2020

Also you should not use "length" as a variable name, length is the MATLAB function that gives array dimensions (largest array dimension). You will have problems in other parts of your code if you then try to use this function. It is also confusing to people who might look at your code and expect that length is a function not a variable name.

I think you could probably do this whole calcuation without loops (vectorize) it.

Jon
on 23 Nov 2020

If I understand your calculation correctly you should be able to do it like this without loops at all

T = [1 2 ; 3 4 ; 5 6 ; 7 8 ; 9 10];

% get components of vector going from start point to each row

delta = T - T(1,:)

% calculate the magnitude of each vector

L = sqrt(delta(:,1).^2 + delta(:,2).^2) % note .^ does element by element

% calculate the force

force = 2.2*(10./L).^3 - (10 ./L).^2 % note ./ and .^ for element by element operation

% the first row will be NaN as the magnitude is zero in the denominator

% you can get rid of this row if you want

force = force(2:end)

Jon
on 23 Nov 2020

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.

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

Start Hunting!
## 1 Comment

## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/658928-how-do-i-get-a-loop-to-calculate-for-each-value-of-a-formula-not-just-the-last-n-of-the-input-n#comment_1154753

⋮## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/658928-how-do-i-get-a-loop-to-calculate-for-each-value-of-a-formula-not-just-the-last-n-of-the-input-n#comment_1154753

Sign in to comment.