I'm trying to execute a custom function within MatLab, such that x which is a vector is actually the exponent of a constant e. I've tried placing the dot in numerous places, but it keeps throwing an error which is telling me to use the . before the ^, which is not what I want to do on this occasion. Y needs to return a vector and not a constant.
x = [0:0.1:1];
function y = hyperT(x)
e = exp(1);
y = ((e^x*2)-1)/((e^x*2)+1);
end
I've taken the . out for the purpose of this thread.
To get a vector, you can use (MATLAB power operator):
y = ((e.^x*2) - 1) ./ (e.^(x*2) + 1);
The . operator basically means "element-wise". For example, if you are multiplying two vectors, x = [x1, x2, x3] and y = [y1, y2, y3], then using the .* operator multiplies each element by the corresponding element in the other vector, while using the * operator without the . performs an inner product (matrix multiplication):
x.*y = [x1y1, x2y2, x3y3]
x*y = error (inner matrix dimensions must agree)
x'*y = [x1y1, x2y1, x3y1;
x2y1, x2y2, x3y2;
x1y3, x2y3, x3y3]
x*y' = x1y1 + x2y2 + x3y3
Note that the ' in the above transposes the vector.
Some operators automatically broadcast because their use is un-ambiguous. Thus you do not need the . with the + and - operators. Oddly enough, the division operator does not auto-broadcast, so you need to use ./ there (MATLAB rdivide). I am not sure what it is doing when you omit the ., but it seems to be well defined and consistent at least.
In general, you can perform any operation (even one that you define) element-wise between two vectors, or between a constant and a vector, by using bsxfun (MATLAB bsxfun). For example, to perform the power operation that you are asking about, you could do:
bsxfun(@power, e, x)
or
bsxfun(@power, e, x*2)
This is actually a super-efficient way to do a lot of neat things, but in your case the functionality is already built in with .^.
Edit: Added some links
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With