Cannot use operator ^ on a vector value - matlab

function[df] = getDiscountFactor(t,T,r,i)
y=getYearFraction(t,T);
a=r(i,1)
df=1/((1+a)^y);
end
This is my code, thing is that y cannot do the (1+a)^y operation because it says it's a vector, but it is only a vector value r(i,1). When I call it in command line it prints a as 0.03 and then it shows this error
a =
0.0300
Error using ^
Inputs must be a scalar and a square
matrix.
To compute elementwise POWER, use
POWER (.^) instead.
If i use .^ operator problem is solved but df gets into a vector and I need it to be a single number.

You've checked the first input to see that it's a scalar, so that presumably means the other input, y, is not a square matrix. If you check what y is too, you will probably see what's gone wrong.
And if not, does matlab have a function that tells you what type matlab thinks an object is? Run that on a and on y. Or to be extra pedantic, run that on 1+a. That should clear things up.

Related

Vectorization of function in Matlab

I'm trying to vectorize one function in Matlab, but I have a problem with assigning values.
function [val] = clenshaw(coeffs,x)
b=zeros(1,length(coeffs)+2);
for k=length(coeffs):-1:2
b(k)=coeffs(k)-b(k+2)+2*b(k+1).*x;
end
val=coeffs(1)-b(3)+b(2).*x;
The purpose of this function is to use Clenshaw's algorithm to compute a value of one polynomial with coefficients "coeffs" at point x.
It work fine when x is a single value, but I'd like it to work with vector of arguments too.
When I try to pass a vector I get an error:
Unable to perform assignment because the left
and right sides have a different number of
elements.
Error in clenshaw (line 7)
b(k)=coeffs(k)-b(k+2)+2*b(k+1).*x;
I understand that there is a problem, because I'm trying to assign vector to a scalar variable b(k).
I tried making b a matrix instead of a vector, however I still cannot get the return output I'd like to have which would be a vector of values of this function at points from vector x.
Thank you for helping and sorry if something isn't entirely clear, because English is not my native language.
The vectorized version of your function looks like this:
function [val] = clenshaw(coeffs,x)
b=zeros(length(x),length(coeffs)+2);
for k=length(coeffs):-1:2
b(:,k)=coeffs(k)-b(:,k+2)+2*b(:,k+1).*transpose(x);
end
val=coeffs(1)-b(:,3)+b(:,2).*transpose(x);
end
b needs to be a matrix. In your loop, you have to perform every operation per row of b. So you need to write b(:,k) instead of b(k). Since b(:,k) is a vector and not a scalar, you also have to be careful with the dimensions when using the .* operator. To get the correct results, you need to transpose x. The same goes for the calculation of val. If you don't like the transposition, just swap the rows and cols of b and you get this:
function [val] = clenshaw(coeffs,x)
b=zeros(length(coeffs)+2, length(x));
for k=length(coeffs):-1:2
b(k,:)=coeffs(k)-b(k+2,:)+2*b(k+1,:).*x;
end
val=coeffs(1)-b(3,:)+b(2,:).*x;
end
However, the first version returns a column vector and the second a row vector. So you might need to transpose the result if the vector type is important.

Symbolic Math Toolbox hitting divide by zero error when it used to evaluate to NaN

I've just updated to Matlab 2014a finally. I have loads of scripts that use the Symbolic Math Toolbox that used to work fine, but now hit the following error:
Error using mupadmex
Error in MuPAD command: Division by zero. [_power]
Evaluating: symobj::trysubs
I can't post my actual code here, but here is a simplified example:
syms f x y
f = x/y
results = double(subs(f, {'x','y'}, {1:10,-4:5}))
In my actual script I'm passing two 23x23 grids of values to a complicated function and I don't know in advance which of these values will result in the divide by zero. Everything I can find on Google just tells me not to attempt an evaluation that will result in the divide by zero. Not helpful! I used to get 'inf' (or 'NaN' - I can't specifically remember) for those it could not evaluate that I could easily filter for when I do the next steps on this data.
Does anyone know how to force Matlab 2014a back to that behaviour rather than throwing the error? Or am I doomed to running an older version of Matlab forever or going through the significant pain of changing my approach to this to avoid the divide by zero?
You could define a division which has the behaviour you want, this division function returns inf for division by zero:
mydiv=#(x,y)x/(dirac(y)+y)+dirac(y)
f = mydiv(x,y)
results = double(subs(f, {'x','y'}, {1:10,-4:5}))

Subscripted assignment dimension mismatch

here is the code listing and i got the above mentiond error at line nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c))); please let me now what is wrong with my code as i m new to matlab
for r = 1:numb_of_nest % for each particle
for c = 1:4
u=randn(size(nests(r,c)))*sigma;
v=randn(size(nests(r,c)));
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
% Apply simple bounds/limits
ns_tmp=nests(r,c);
I=ns_tmp<Lb(c);
ns_tmp(I)=Lb(I);
% Apply the upper bounds
J=ns_tmp>Ub(c);
ns_tmp(J)=Ub(J);
% Update this new move
nests(r,c)=ns_tmp;
end
end
This error happens when you assign a value of some dimension m x n to a subscripted variable of different dimension.
In your case, assuming nests has no third dimension, you're assigning to a scalar (1x1) variable. This only works if the value you're trying to assign also is a scalar. Since you get the error, it probably isn't. The only place where your dimensions can be non-scalar is stepsize, so to fix this error, make sure stepsize is a scalar value.
According to the definition you gave in an earlier comment (stepsize=0.01*step.*(nests(r,c)-best);), this problem translates to make sure best is a scalar value. Possibly by subscripting, I can't tell you exactly how since I don't know what best is.
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
Here you're assigning a value to the variable step, but then using a different variable called stepsize that hasn't been assigned a value anywhere in this code. Is this intentional? If not, stepsize is probably some leftover variable from previous code which is messing up the dimensions and giving you this error.
In addition to the above, is nests an ordinary two-dimensional matrix in your code? If so, taking size(nests(r,c)) every time is unnecessary - since you're giving two subscripts, the result is only going to be 1 all the time. Or is nests a cell array perhaps? In that case, you might want to index using curly braces { } instead of ordinary parantheses, to get the size of the matrix that's sitting inside the cell.

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.

Scilab: "first and second input arguments must be real at line 53 of function histplot"

Why does this piece of code fail in Scilab?
N=1000;
U=rand(N, 1);
X=(9*U - 1)^(1/3);
histplot(200, X);
Most likely the code fails because X is not real. This can happen if U is smaller than 1/9, which means that you take the third root of a negative number.
You can find problematic values of U by checking for whether the values in X are real.
Is there a '.' per element operator missing?
X=(9*U - 1).^(1/3);
EDIT:
As Jonas points out Scilab histplot won't accept complex values as argument. MATLAB on the other hand fails because of the missing 'per element' operator.