What does VAR(:,:) mean in Matlab? - matlab

I am trying to understand the following code I found online and am having trouble with the first line:
errors(:,:) = (errors(:,:)*trials + 0.5)./(trials + 1);
PBIerr = (errors(:,2)-errors(:,3))./(errors(:,2)+errors(:,3));
What does (:,:) stand for in Matlab? Is it some kind of "select all"?
Thanks in advance!

Yes. The colon operator is a "select all, from this index" operator. Note that in the first line, its unnecesary as long as errors was already 2D, as "select the entire variable" is not something you need to specify, its by default. So it could have been
errors = (errors*trials + 0.5)./(trials + 1);.
If errors had more dimensions than 2, then the colon operator in the right hand side of the equal sign is doing something, in particular "A(:,:) reshapes all elements of A into a two-dimensional matrix. This has no effect if A is already a matrix or vector.". The one in the left hand side is useless anyway, as that line overwrites the variable.
The use of the colon operator in the second line however is well justified.
There are few other things that the colon operator means in MATLAB, read them all here: https://uk.mathworks.com/help/matlab/ref/colon.html

Related

MATLAB - transpose and extract a matrix in a line

old_mat = [1,2,3; 4,5,6];
new_mat = old_mat'(2:end, :);
new_mat = (old_mat')(2:end, :);
I would like to transpose and extract a matrix but I fail with these tries.
Is it possible to do them in a line?
Parentheses ( ) should usually[1] be the last thing in a Matlab expression. This is why an expression like a(1)(1) will give the error:
Error: ()-indexing must appear last in an index expression.
And your examples give the error
Error: Unbalanced or unexpected parenthesis or bracket.
You should, as rahnema1 suggested, extract the columns and transpose rather than trying to transpose and extract rows.
new_mat = old_mat(:, 2:end).'
Note, I've used .' which is shorthand for transpose, not ' which is shorthand for ctranspose and should be avoided unless specifically required!
[1] There are always exceptions to the rule! Here are examples of where you can put things immediately after ).
Referring to table columns or struct fields by a string, where T.('var')(1) and T.var(1) are equivalent.
Use the dot operator, which is again a feature of using structs, like S(1).var.
Generally though, if you're trying to add code next to a closing ) for simple matrix operations then there is probably a syntax error.

subscript indices must be either positive integers less than 2^31 or logicals

I'm quite new to Matlab/Octave programming, but have this one issue that I can't seem to solve.
I wrote the following which is actually a quite straight forward calculation on an option price using the Black Scholes Formula (just to give you some background). However, I do constantly get the following error msg:
"subscript indices must be either positive integers less than 2^31 or logicals"
One would think that this explaines it quite nicely and I know there've been questions on it before. The thing that causes troubles, however, is that I am not using any kind of subscript index in my code at all.
Here is my code:
function v=BS_LBO_strike_call(s,T,sigma,r,q,l,alpha)
d1=(log(alpha*l./s) + (r-q-0.5*sigma^2)*T)/(sigma*sqrt(T));
d2=(log(alpha*l./s) - (r-q+0.5*sigma^2)*T)/(sigma*sqrt(T));
d3=(log(alpha*l./s) + (r-q+0.5*sigma^2)*T)/(sigma*sqrt(T));
d4=(log(alpha*l./s) + (r-q-0.5*sigma^2)*T)/(sigma*sqrt(T));
v = exp(-r*T)*s(0.5*sigma^2./(r-q)*(l./s).^(2*(r-q)./sigma^2).*normcdf(d1) - 0.5*sigma^2./(r-q)*alpha.^(-2*(r-q)./sigma^2).*exp((r-q).*T).*normcdf(d2) + alpha.exp*((r-q).*T).*normcdf(d3) - (l./s).*normcdf(d4));
So, I can't seem to figure out what doesn't work out for Octave.
I would highly appreciate if you could maybe shed some light on this. I'm convinced there must be something minor that I overlook
The source of your issues lies in your last line. You have the following:
v = exp(-r * T) * s(0.5 * sigma^2 ....
I think that you have omitted an * between the s and the opening parenthesis because as it is now, everything after that parenthesis is being treated as a subscript into s. This is the root cause of the error you are getting because what follows is likely not an integer or logical.
There is one other point in that line that is likely going to lead to some errors as well. You have the following as part of that statement.
alpha.exp*((r-q).*T) ...
Unless alpha is a struct (I'm sure it's not because you haven't used it that way previously), you will likely want something else besides the . between alpha and exp. Maybe another *?

MatLab latex title doesn't work for powers (^)

In MatLab (R2015a), I want to style the title of my plots using latex.
This is working fine for some functions, but not if there's a power in the equation.
The below code works, and shows a formatted title to the right, and an unformatted title to the left.
It shows the warning:
Warning: Error updating Text.
String must have valid interpreter syntax: y = x^2
syms x y
eq = y == x^2;
subplot(1,2,1)
ezplot(eq)
title(latex(eq),'interpreter','latex')
eq = y == x+2;
subplot(1,2,2)
ezplot(eq)
title(latex(eq),'interpreter','latex')
EDIT:
I just found out I can get it to work by appending $ on both sides. But it seems weird that I would have to do this.
So this works:
title(strcat('$',latex(eq),'$'),'interpreter','latex')
Solution
The problem can be solved easily by adding $-signs before and after the generated LaTeX-expression. So you can change your «title-lines» to:
title(['$',latex(eq),'$'],'interpreter','latex')
An alternative is to use strcat as proposed in your question.
Explanation
Since you basically answered the question yourself already, I'm going to explain why it happened. Hopefully after reading this, it's no longer 'weird' behaviour. If you choose to use the LaTeX-interpreter in Matlab, you really get a LaTeX-interpreter. This means that the provided string must be valid LaTeX-syntax.
Using ^ outside a math-environment is considered invalid syntax because it is a reserved character in LaTeX. Some interpreters automatically add the $ before and after in this case, but throw a warning at the same time.
The output of the latex-function in Matlab is provided without the $-signs. This way you can combine outputs and concatenate if needed without creating a mess with $-signs.
To change to the math-environment in LaTeX you can use the already mentioned shortcut $...$. An alternative way is to use \begin{math} your_equation \end{math}. It produces the same result for your equations and can be used here for demonstration purposes. The following line would do the same job, but is a bit longer to write:
title(['\begin{math}',latex(eq),'\end{math}'],'interpreter','latex')
Now, the reason why only one of your equations is displayed correctly, lies in the invalid character ^ in y = x^2. Matlab then chooses interpreter none and therefore displays the string unformatted. The +-sign in y = x + 2 is valid outside a math-environment, so it gets displayed correctly (but is not interpreted in a math-environment).

Finding the first element less than a certain value in an unsorted vector (MATLAB)

Pretty simple, and I thought I knew what I was doing, but apparently not. Anyways.
I need to find the first element in a vector that is less than a specific value. Here is the code that I have been using:
t = 0:0.01:5;
u = ((2)*exp(-10.*t).*cos((4.*sqrt(6)).*t) + ((5)./sqrt(6)).*exp(-10.*t).*sin((4.*sqrt(6)).*t));
for a = 1:size(u)
if u(a) < (0.05)
disp(a)
break
end
end
The value that I'm trying to find is the first element less than 0.05, however, when I run my code, I don't get anything.
What could I be doing wrong?
Thanks!
#user2994291 has correctly pointed out where your loop based solution is going wrong (+1).
However I would also add that what you are trying to do can simply be accomplished by:
find(u < 0.05, 1, 'first')
Technically, the third input is not necessary - you could just use:
find(u < 0.05, 1)
However, I seem to recall reading at some point that find will work faster if you provide the third input.
The upper bound of your for loop is probably equal to 1.
In your case, u is a row vector (can't say 100% for sure in MATLAB as I only have access to GNU Octave right now), but calling size(u) will probably give back [1 501] as an answer. Your for-loop will select 1 as upper bound.
Try replacing size(u) with size(u,2) or, even better, with length(u). I get a = 24 as an answer.
Edit:
from your questions I assume you are a MATLAB beginner, therefore I strongly advise you to look into the built-in debugger (you can add breakpoints by clicking on the left vertical bar next to the desired line of code), this would have helped you identify the error with ease and will save you a lot of time in the future.

Using a value from a matrix as a multiplier in an equation?

Started using MatLab a couple of weeks ago, I don't know much proper syntax / terminology.
I'm trying to use a value in a 3x1 matrix as a multiplier in an equation later.
This is to draw a circle with radius and centre point defined by values input by the user.
I have a pop-up window, the values are input by the user and stored in this 3x1 cell (labelled answer).
How do I use the second value of that matrix, answer(2), in the following equation:
x = 'answer(2)' * cos(theta) + xCentre;
This error message appears:
Error using .*
Matrix dimensions must agree.
Error in Disks (line 40)
x = 'answer(2)'.* cos(theta) + xCentre;
In MATLAB, apostrophes ('') define a string. If the name of your matrix is answer, you can refer to its second value by the command answer(2) as mentioned by #Schorsch. For more infos on vectors and matrices, you can check this site.
In addition to what the previous answer says, its important to understand what exactly you are doing before you do it. Only add the ('') if you are defining a string, which generally occurs when dealing with variables. In your case, you simply have a matrix, which is not a string, but rather a set of numbers. You can simply do answer(2) as aforementioned, because answer(2) calls up the second value in your matrix while 'answer(2)' has you trying to define some variable that does not exist.
the most important thing is truly understanding what you are doing to avoid the basic syntax errors.