MATLAB Answers

Calculate with same amount on every date and adjust when date changes (for-loop)

1 ビュー (過去 30 日間)
buhmatlab
buhmatlab 2020 年 4 月 28 日
回答済み: Peter Perkins 2020 年 4 月 30 日
Hi,
I’ve got three column vectors (300x1) Date, VariousA, Amount (Amout has only one Starting value in row 1) and I wanna perform a calculation for each row of my column vectors depending on the datetime-vector (Date). If the date does not change, the amount in the calculation should not change either. If the date changes, I wanna sum up all the results of the calculations of the previous date and add the sum to the amount (Amount vector) of the previous date.
The following example is based on the table below:
First, the Amount-Vector only contains a value in the first row (100). The calculation delivers 60. Since the date in the next row stays the same, the amount remains as well - the calculation delivers 30. Since the date in row 3 changes, I now want to adjust my amount. The sum of the results on the previous date is 90 which should be added to the amount of the previous date. The new amount in row 3 is therefor 190 and the calculation delivers 85.5 which need to be added to 190 in the next row because the date in row 4 changes again, and so on…
I hope it has become clear. Is there anybody able to help?
MANY THANKS IN ADVANCE!
EDIT: I've figured out this Code but it does not work at all:
if i>1 & Date(i)>Date(i-1)
Amount(i) = sum(Result(find(Date==Date(i-1)))) + Amount(i-1);
elseif i>1 & Date(i)==Date(i-1)
Amount(i) = Amount(i-1);
end
Result(i)=VariousA(i)*Amount(i);
TABLE:
| Date | VariousA | Amount | Result | HelpColumn |
|------------- |---------- |-------- |-------- |-------------- |
| 28-Jul-2001 | 0.6 | 100 | 60 | 100*0.6 |
| 28-Jul-2001 | 0.3 | 100 | 30 | 100*0.3 |
| 29-Jul-2001 | 0.45 | 190 | 85.5 | 190*0.45 |
| 04-Aug-2001 | -0.7 | 275.5 | -192.5 | 275.5*(-0.7) |
| 04-Aug-2001 | 0.1 | 275.5 | 27.55 | 275.5*0.1 |
| 05-Aug-2001 | 0.4 | 110.55 | 44.22 | 110.55*0.4 |

  2 件のコメント

Walter Roberson
Walter Roberson 2020 年 4 月 29 日
If you used a timetable() then retime() might help.
buhmatlab
buhmatlab 2020 年 4 月 29 日
My code actually works, there was only a bug. Thank you anyway

サインインしてコメントする。

採用された回答

buhmatlab
buhmatlab 2020 年 4 月 29 日
if i>1 & Date(i)>Date(i-1)
Amount(i) = sum(Result(find(Date==Date(i-1)))) + Amount(i-1);
elseif i>1 & Date(i)==Date(i-1)
Amount(i) = Amount(i-1);
end
Result(i)=VariousA(i)*Amount(i);

  0 件のコメント

サインインしてコメントする。

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2020 年 4 月 30 日
This is almost certainly simple to do with a timetable, no looping needed. Probably either retime or rowfun, plus cumsum. But honestly, I can't understand the description.

  0 件のコメント

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by