Clear Filters
Clear Filters

How to write a code for an equation in such a way that it add previous results repetitively?

2 views (last 30 days)
I want calculate distance between to points as:
X1 = X(1:end-1); X2 = X(2:end);
Y1 = Y(1:end-1); Y2 = Y(2:end);
xi = 5.55e5;
x = xi + sqrt((X2-X1).^2 + (Y2-Y1).^2);
But I want like say first value of x is = xi (5.55e5) and in the second value of x, xi will be added and in the next value the previoous one will be add and so on... I mean after first value equation of x will move in a way that the previous one will be added into the results. How can I write x equation in matlab? For example
if X = [2 3 4 5 6 7 8 9];
X1 = X(1:end-1); X2 = X(2:end);
xi = 5.55e5;
Now if I compute x as (assuming Y2 = Y1, and Y2-Y1 is 0.
x1 = 5.55e5 + sqrt(3 - 2).^2
x1 = = 555001;
x2 = x1 + sqrt(4 - 3).^2
and so on....
How to write in MATLAB equation/code?

Sign in to comment.

Accepted Answer

Torsten on 15 Nov 2022
xi = 5.55e5;
X = ...;
Y = ...;
x = [xi,sqrt((X(2:end)-X(1:end-1)).^2 + (Y(2:end)-Y(1:end-1)).^2)]; % assumes X and Y are row vectors
x = cumsum(x)

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!