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 ?

답변 (1개)

James Tursa
James Tursa 2016년 11월 4일
편집: James Tursa 2016년 11월 4일
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

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 ?

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

질문:

2016년 11월 4일

편집:

2016년 11월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by