Filter löschen
Filter löschen

Pecentage change of variable

4 Ansichten (letzte 30 Tage)
Benjamin
Benjamin am 8 Feb. 2012
Hi everyone, I'm very sorry for that question but I'm all new to Matlab and I'm still on my way to figure it out. So, the problem is that I want generate a return (i.e. percentage change) variable. I imported the absolut values of the variable from Excel and now I'd like to replace them by their relative change. More precisely, the value of x_t_ with respect to its predecessor x_t-1_How can I do that? Any answer would be very much appreciated! I guess it's a very easy question for you but it would very much ease the start for me! Thanks, Ben. P.S.: I also got the Financial Toolbox which might help here...

Antworten (4)

Frank
Frank am 8 Feb. 2012
This could do it:
>> a = [1 1.1 1.2 1 0.9 1.3];
>> b = [diff(a) NaN];
>> b./a
ans =
0.1000 0.0909 -0.1667 -0.1000 0.4444 NaN
diff returns the difference between two vector elements. It is one element shorter, therefore I added a NaN to the new vector. In the end a element-wise division
Cheers, Frank
  1 Kommentar
Walter Roberson
Walter Roberson am 8 Feb. 2012
... and multiply by 100 for percentage ;-)

Melden Sie sich an, um zu kommentieren.


Benjamin
Benjamin am 8 Feb. 2012
Hi Frank and Walter, thanks very much for the quick answer. One little follow-up: when I apply your exact example it works fine, however, if I apply it on my own variable I receive the following error:
>> BondsII = [diff(Bonds) NaN] ??? Error using ==> horzcat All matrices on a row in the bracketed expression must have the same number of rows.
I'm not sure what the problem might be... could be the way my variable is stored? It's currently stored as double. Cheeers Ben

Frank
Frank am 8 Feb. 2012
your elements in Bonds are not aligned in a row they are aligned in a column. have a look at a and then at Bond, then you will see the diff. you could either b = [diff(Bond); NaN]; or b = [diff(Bond') NaN];
where ' transposes the matrix/vector Bond

Walter Roberson
Walter Roberson am 9 Feb. 2012
Is your data a vector or an array?
Vector, either row or column vector:
BondsII = [diff(Bonds(:)); NaN];
(BondsII ./ Bonds(:) .* 100) .'
The final .' is just there to make a row vector out of the results
Array, and assuming you want to process across rows (which is not the default):
BondsII = [diff(Bonds,[],2), NaN(size(Bonds,1),1)];
BondsII ./ Bonds .* 100
  1 Kommentar
Isaac
Isaac am 8 Aug. 2013
I have a slight problem when i used this.
For example, I have 13.39 in data(2) and 13.06 in data(1) so the current percent diff should be -2,46 but i am getting +2.52.
Where did i go wrong?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Financial Toolbox finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by