Reputation: 47
I have a problem with storing results in a matrix. a is my time series with a certain rate. Now I would like to have that rate quarterly, so I did the following:
a = [1 4.2; 2 3.9; 3 3.7; 4 3.9; 5 4.1; 6 4.3; 7 4.2; 8 4.1; 9 4.4; 10 4.5; 11 5.1; 12 5.2;13 5.8]
for K = 1:3:10;
result(K, 1) = a(K+3, 2)-a(K, 2)
end
Unfortunately, the result vector is now a 10x1 vector, but actually I would like it to be a 4x1 vector only with the 4 quarterly values. For the given example my desired output would be [-0.3 0.3 0.3 1.3].
Anyone an idea how to do so? Any help appreciated!
Upvotes: 1
Views: 46
Reputation: 18905
As explained in Patrick Happel's comment, in your example, K
have will values from [1 4 7 10]
. By accessing result(K, 1)
for K = 10
, your result
array "automatically" will have a size of 10x1
.
To prevent that, you can "precalculate" the indices from K
and access the corresponding elements in a
directly without using any loop.
Here are the codes next to each other:
% Input
a = [1 4.2; 2 3.9; 3 3.7; 4 3.9; 5 4.1; 6 4.3; 7 4.2; 8 4.1; 9 4.4; 10 4.5; 11 5.1; 12 5.2;13 5.8]
% Using loop
for K = 1:3:10;
result(K, 1) = a(K+3, 2)-a(K, 2);
end
result
% Using precalculated indices
K = 1:3:10;
result = a(K+3, 2)-a(K, 2)
And, the outputs:
a =
1.0000 4.2000
2.0000 3.9000
3.0000 3.7000
4.0000 3.9000
5.0000 4.1000
6.0000 4.3000
7.0000 4.2000
8.0000 4.1000
9.0000 4.4000
10.0000 4.5000
11.0000 5.1000
12.0000 5.2000
13.0000 5.8000
result =
-0.30000
0.00000
0.00000
0.30000
0.00000
0.00000
0.30000
0.00000
0.00000
1.30000
result =
-0.30000
0.30000
0.30000
1.30000
Hope that helps!
Upvotes: 3