Why won't the following operations work in Matlab - matlab

If input into a Matlab script, the following are deemed as unacceptable:
i) 8.8*e-2
ii) 3.2e1.5
iii) 1.25e+005
But why doesn't i), ii) and iii) work?
Is it because e is undefined?
I would have thought the reason for i) is because of the unnecessary *, but there is no * in either ii) or iii) and I believe they are also unacceptable.

i:
>> 8.8*e-2
Undefined function or variable 'e'.
This is self explanatory; you're asking to multiply with the * operator. It should be 8.8e-2
ii:
>> 3e1.5
3e1.5
↑
Error: Unexpected MATLAB expression.
From Wikipedia (emphasis mine):
Scientific notation (also referred to as scientific form or standard index form, or standard form in the UK) is a way of expressing numbers that are too big or too small to be conveniently written in decimal form. [...]
In scientific notation, all numbers are written in the form m × 10^n
(m times ten raised to the power of n), where the exponent n is an integer, and the coefficient m is any real number.
You want to use
>> 3*10^1.5
ans =
94.8683
iii:
>> 1.25e+005
ans =
125000
What's the problem?
2 ARE acceptable: 6,10 and .0
Can you clarify this question? It doesn't seem to be about scientific notation.
>> 6,10
ans =
6
ans =
10
>> .0
ans =
0

Related

matlab Pythagorean Theorem without using for

I am doing a matlab homework and I solved the next problem. and the grader say it is a correct answer. I used for in the program and we didn't take yet in the course. can someone suggest a program with out for or if.
Write a function called pitty that takes a matrix called ab as an input argument. The matrix ab has exactly two columns. The function should return a column vector c that contains positive values each of which satisfies the Pythagorean Theorem, a2 + b2 = c2, for the corresponding row of ab assuming that the two elements on each row of ab correspond to one pair, a and b, respectively, in the theorem. Note that the built-in MATLAB function sqrt computes the square root and you are allowed to use it.
my code
function c = pitty(ab)
[n , m] = size(ab)
for i = 1:n
c(i) = sqrt(ab(i,1)^2 + ab(i,2)^2)
end
c = c'
end
You can square each element of the matrix by using the .^2 operator. Then summing along each row sum(...,2) and finally taking the root.
ab = [1,2;3,4;5,6]
c = sqrt(sum(ab.^2,2));
No for needed for that.
MATLAB has a function for this called hypot short for hypotenuse. The main reason for existence of it is that it takes care of overflow (and underflow) problem. If the input values are too large (or small) the square of them (or sum of square of them) can be larger (smaller) than the largest (smallest) representable value in floating-point, while still the corresponding c value is representable. In your case you can use it like this:
c=hypot(ab(:,1), ab(:,2));
Cleve Moler, one of the founders of MathWorks and original author of MATLAB, tells the story behind hypotin this article.
I'd recommend hypot as in Mohsen's answer.
Just for some variety, here's another approach, using complex numbers. This approach avoids overflow and underflow, just like hypot does:
abs(ab*[1; 1j])
Examples (taken from Cleve Moler's post):
>> ab = [1e154 1e154]; %// LARGE VALUES: possible overflow
>> sqrt(sum(ab.^2,2))
ans =
Inf %// overflow
>> hypot(ab(:,1), ab(:,2))
ans =
1.414213562373095e+154 %// correct result
>> abs(ab*[1; 1j])
ans =
1.414213562373095e+154 %// correct result
>> ab = [3e-200 4e-200]; %// SMALL VALUES: possible underflow
>> sqrt(sum(ab.^2,2))
ans =
0 %// underflow
>> hypot(ab(:,1), ab(:,2))
ans =
5.000000000000000e-200 %// correct result
>> abs(ab*[1; 1j])
ans =
5.000000000000000e-200 %// correct result

Is there any way to increase 'realmax' in MATLAB?

realmax on my machine is:
1.7977e+308
I know I have to write my code in a way to avoid long integer calculations, but is there any way to increase the limit?
I mean something like gmp library in C
You may find vpa (variable- precision arithmetic) helpful:
R = vpa(A) uses variable-precision arithmetic (VPA) to compute each element of A to at least d decimal digits of accuracy, where d is the current setting of digits.
R = vpa(A,d) uses at least d significant (nonzero) digits, instead of the current setting of digits.
Here's an example how to use it:
>> x = vpa('10^500/20')
ans =
5.0e498
Note that:
The output x is of symbolic (sym) type. Of course, you shouldn't convert it to double, because it would exceed realmax:
>> double(x)
ans =
Inf
Use string input in order to avoid evaluating large input values as double. For example, this doesn't work
>> vpa(10^500/20)
ans =
Inf
because 10^500 is evaluated as double, giving inf, and then is used as an input to vpa.

matlab wrong modulo result when the divident is raised to a power

Just wondering... I tried doing by hand (with the multiply and square method) the operation (111^11)mod143 and I got the result 67. I also checked that this is correct, in many online tools. Yet, in matlab plugging:
mod(111^11,143)
gives 127! Is there any particular reason for this? I didn't find anything in the documentation...
The value of 111^11 (about 3.1518e+022) exceeds the maximum integer that is guaranteed to be represented exactly as a double, which is 2^53 (about 9.0072e+015). So the result is spoilt by insufficient numerical precision.
To achieve the correct result, use symbolic computation:
>> syms x y z
>> r = mod(x^y, z);
>> subs(r, [x y z], [111 11 143])
ans =
67
Alternatively, for this specific operation (modulo of a large number that is expressed as a product of small numbers), you can do the computation very easily using the following fact (where ∗ denotes product):
mod(a∗b, z) = mod(mod(a,z)∗mod(b,z), z)
That is, you can apply the modulo operation to factors of your large number and the final result is unchanged. If you choose factors sufficiently small so that they can be represented exactly as double, you can do the computation numerically without any loss of precision.
For example: using the decomposition 111^11 = 111^4*111^4*111^3, since all factors are small enough, gives the correct result:
>> mod((mod(111^4, 143))^2 * mod(111^3, 143), 143)
ans =
67
Similarly, using 111^2 and 111 as factors,
>> mod((mod(111^2, 143))^5 * mod(111, 143), 143)
ans =
67
from the matlab website they recommend using powermod(b, e, m) (b^e mod m)
"If b and m are numbers, the modular power b^e mod m can also be computed by the direct call b^e mod m. However, powermod(b, e, m) avoids the overhead of computing the intermediate result be and computes the modular power much more efficiently." ...
Another way is to use symfun
syms x y z
f = symfun(mod(x^y,z), [x y z])
f(111,11,143)

MATLAB operators as functions

I was just curious that whether all operators in MATLAB are internally implemented as functions? We have equivalent functions for almost all MATLAB operators. plus for +, minus for -, eq for == and transpose for '.
Most operators are represented by functions, yes.
A thorough list is provided on the MathWorks page Implementing Operators for Your Class, reproduced here:
a + b plus(a,b) Binary addition
a - b minus(a,b) Binary subtraction
-a uminus(a) Unary minus
+a uplus(a) Unary plus
a.*b times(a,b) Element-wise multiplication
a*b mtimes(a,b) Matrix multiplication
a./b rdivide(a,b) Right element-wise division
a.\b ldivide(a,b) Left element-wise division
a/b mrdivide(a,b) Matrix right division
a\b mldivide(a,b) Matrix left division
a.^b power(a,b) Element-wise power
a^b mpower(a,b) Matrix power
a < b lt(a,b) Less than
a > b gt(a,b) Greater than
a <= b le(a,b) Less than or equal to
a >= b ge(a,b) Greater than or equal to
a ~= b ne(a,b) Not equal to
a == b eq(a,b) Equality
a & b and(a,b) Logical AND
a | b or(a,b) Logical OR
~a not(a) Logical NOT
a:d:b colon(a,d,b) Colon operator
a:b
colon(a,b)
a' ctranspose(a) Complex conjugate transpose
a.' transpose(a) Matrix transpose
command line output display(a) Display method
[a b] horzcat(a,b,...) Horizontal concatenation
[a; b] vertcat(a,b,...) Vertical concatenation
a(s1,s2,...sn) subsref(a,s) Subscripted reference
a(s1,...,sn) = b subsasgn(a,s,b) Subscripted assignment
b(a) subsindex(a) Subscript index
Another good place to look for a list is actually the documentation for bsxfun, which applies any element-wise function with very powerful virtual data replication.
Often useful is vertcat. horizontal vs. vertical concatenation with a comma separated list:
>> c = {'a','b'};
>> horzcat(c{:}) % [c{1} c{2}]
ans =
ab
>> vertcat(c{:}) % [c{1};c{2}]
ans =
a
b
In addition to many other documented operators with named functions (colon,transpose,etc.), there are a couple undocumented ones that you can access with builtin:
parenthesis
>> x = [4 5 6];
>> builtin('_paren',x,[2 3]) % x([2 3])
ans =
5 6
curly braces
>> c = {'one','two'};
>> builtin('_brace',c,2) % c{2}
ans =
two
struct field access (dot)
>> s = struct('f','contents');
>> builtin('_dot',s,'f') % s.f
ans =
contents
However, note that the proper and supported way to use (), {}, or . is via subsref, subasgn, and subindex, depending on the context.
These builtins refer to the operators described in help paren. Also explore the punctuation listed in help punct.
Yes, that's how MATLAB enables operator overloading, by mapping infix operators to named functions.
The documentation lists (by category) the functions invoked by operators. And more here.

Is there anyway to calculate mean of beta distribution with MATLAB?

This is my code for calculate the mean:
syms a b x
f=1/(beta(a,b))*x^(a-1)*(1-x)^(b-1);
int(x*f,x,0,1)
Warning: Explicit integral could not be found.
ans =
int((x*x^(a - 1)*(1 - x)^(b - 1))/beta(a, b), x == 0..1)
How can I fix this?
This is my result for TryHArd's:
syms x a b
f=int(x^(a-1)*(1-x)^(b-1),x,0,1)
Warning: Explicit integral could not be found.
f =
piecewise([0 < real(a) and 0 < real(b), beta(a, b)], [real(a) <= 0 or real(b) <= 0, int(x^(a - 1)*(1 - x)^(b - 1), x == 0..1)])
My result did not show the same gamma(a)*gamma(b)/gamma(a+b) as TryHard did.
I assume by beta you mean
beta(z,w) = integral from 0 to 1 of t.^(z-1) .* (1-t).^(w-1) dt.
Then break down the problem:
>> int((x^(a-1))*((1-x)^(b-1)),x,0,1)
ans =
gamma(b)*gamma(a)/gamma(a+b)
The desired integral is equivalent to:
>> bint=int((x^(a-1))*((1-x)^(b-1)),x,0,1);
>> int( x*((x^(a-1))*((1-x)^(b-1)))/bint,x,0,1)
ans =
a/(a+b)
(This was computed with an earlier version of the Matlab SMT (on R14), but should serve as a guide.)
The mean of the Beta distritution is 1/(1+b/a). See for example here
Wolfram alpha is capable of it.
Computing the definite integral directly exceeds maximum standard computation time, but it can find the indefinite integral. Limiting that expression to x between 0 and 1, means simply equating x to 1. This results in this expression, the alternate form of which is the standard form of the mean of the beta distribution.
Wolfram Mathematica (& Alpha) is simply better at symbolic math than MuPad. I'd advise to use MATLAB only for what it rocks at: numerical math. Other than perhaps some fringe cases, I do not expect MuPad to ever come close to what has been achieved by Wolfram.
If you need the result for some specific parameters alpha and beta, you can use betastat. This function can be used also with vectors, like that:
A=[4 4 4];
B=[5 6 7];
[m,v]=betastat(A,B)
This will give you a 3-elements vector for both m (mean) and v (variance). For this example, m will be the means of beta(4,5), beta(4,6) and beta(4,7). (Note that "beta" here denotes the distribution, not the beta-function, like beta function on Matlab).
If you need a general (mathematical) solution, see Rody's answer. Wolfram is much appropriate for this.
EDIT: You can define f (in your code) by the function betapdf instead of the whole formula you wrote over there.