How to reference previous value in an array without a for loop?

6 views (last 30 days)
Hi,
I have a for loop set up following a similar structure to this:
for i=2:size(data,1)
data.Var3(i)=interp1(ref_data.x,ref_data.y,data.Var2(i))-interp1(ref_data.x,ref_data.y,data.Var2(i-1));
end
Where I use a reference table to interpolate a certain x value from my current data to obtain a corresponding y value, that is done twice per row.
It works, but the data table I'm using has 300,000 rows, so the run time of this loop alone is just under 3 mins in my case (data.Var3 is not being resized after every iteration in the loop).
Doing this operation this way simply takes too long, is there any way you can think of in which I can carry out the operation inside the for loop, without actually putting it inside a loop?
Any help is appreciated,
Thanks!

Accepted Answer

Wan Ji
Wan Ji on 24 Aug 2021
use i=2:size(data,1); data.Var3(i)=interp1(ref_data.x,ref_data.y,data.Var2(i))-interp1(ref_data.x,ref_data.y,data.Var2(i-1));

More Answers (0)

Categories

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

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!