Variable B in a table (type = double) needs to calculated based on Variable A in the same table (type = double), but the key is that Variable B is calculated based on the value of Variable A in both the current row and the previous row. How please ?

Variable B in a table (type = double) needs to calculated based on Variable A in the same table (type = double), but the key is that Variable B is calculated based on the value of Variable A in both the current row and the previous row. I may have to do this in a 'for' loop but I have tried and failed. I tried to use the index 'n' in the for loop as follows:
for n=1:5
a_small.test(n) = a_small.Flow(n)- a_small.Flow(n-1)
end
Any ideas ?

Antworten (1)

When n=1 you are using an index of 0 which will cause an error. What do you want to do for the 1st element since there is no 0'th element to work with? Leave it alone? E.g., start your indexing at 2 instead?
for n=2:5
a_small.test(n) = a_small.Flow(n)- a_small.Flow(n-1)
end

3 Kommentare

Thanks for the reply. So it looks like n has to be 2 in order to access the data in row 1 ? In any case, say I have a data value of 2 in the first row and a date value of 10 in the second row. What I want to do is calculate the difference between the second row and the first row values (i.e. 10 - 2 = 8), and assign the result (8) to the new variable. Is a for loop the best way to do this ? I will have hundreds or thousands of rows of data.
Well, to do a simple difference between adjacent elements you could use the diff function:
a_small.test = [0;diff(a_small.Flow)];
I solved my problem using the following code on a small test table:
for n=2:5
a_small.test(n) = a_small.Flow(n)-a_small.Flow(n-1)
a_small.test(n)
end
Thanks for your feedback. What do you use MatLab for ?

Melden Sie sich an, um zu kommentieren.

Produkte

Tags

Gefragt:

am 4 Nov. 2016

Bearbeitet:

am 5 Nov. 2016

Community Treasure Hunt

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

Start Hunting!

Translated by