Why does MATLAB fail to check the equality of this trigonometric expression - matlab

isequaln() is testing symbolic objects for equality as stated in the documentation. However, this is not the case with the following script.
syms a
f1=cos(a)^2;
f2=1-sin(a)^2;
isequaln(f1,f2)
ans =
logical
0
MATLAB does not return the correct answer. What does MATLAB do when comparing equality for symbolic expressions, compare strings (i.e. a typical scenario for regular expressions), or something else?

At the bottom of the documentation page, there is a section called "Tips", which contains the following item:
isequaln(A,B) checks if A and B are the same size and their contents are syntactically the same expression, treating NaN values as equal. To check whether the mathematical comparison A == B holds for all values of variables in A and B, use isAlways(A == B).
(emphasis mine)
isAlways does what you want:
syms a
f1 = cos(a)^2;
f2 = 1-sin(a)^2;
isAlways(f1 == f2)
This outputs true.
Alternatives:
>> simplify(f1-f2)
ans =
0
>> simplify(f1==f2)
ans =
symtrue

Related

MATLAB isequal function gives wrong answer for symbolic expression

In the following simple code:
syms x
isequal((x+1)^2, x^2+2*x+1)
MATLAB returns false, but two expressions are same!
What is wrong with the code?
These are not exactly the same expressions, and isequal() tests for expression equality. Try for example:
>> isequal(expand((x+1)^2), x^2+2*x+1)
ans =
logical
1
or,
>> isequal(simplify((x+1)^2), simplify(x^2+2*x+1))
ans =
logical
1
PS you could also use isAlways() to compare expressions,
isAlways((x+1)^2 == x^2+2*x+1)
ans =
logical
1

How to assign values to variables in a handle function?

This is simplified but take as an example the following MATLAB function handle:
F = #(x)[x(1)-x(2);x(2)-x(3)]
The system has of course has many solutions. Is it possible to obtain a solution for a function like this one after substituting at least one variable? For example, substituting x(3)=1 the function would become:
G = #(x)[x(1)-x(2);x(2)-1]
And a solution for the other variables can be obtained. I use fsolve and it works quite well for the system of equations I have. Of course what I need to do can be done using the Symbolic Toolbox, but calling it in a big for loop makes it too slow to use for my code.
I'm trying to come up with some code that can return G given F and a set of indices in x to replace with given values.
What you're basically asking to do is have G call F with values in x reassigned based on a logical replacement index index and a set of replacement values values, which is doable but messy since anonymous functions can only have a single executable statement.
The solution is similar to what is done in this answer, but instead of using the functional form for subscripted reference we'll need to use the functional form for subscripted assignment: subsasgn. Here's what it would look like:
F = #(x)[x(1)-x(2); x(2)-x(3)];
values = [3 2 1];
index = logical([0 0 1]);
G = #(x) F(subsasgn(x, struct('type', '()', 'subs', {{index}}), values(index)));
And here's a test:
>> F([3 2 3])
ans =
1
-1
>> F([3 2 1]) % Replace the last element by 1
ans =
1
1
>> G([3 2 3]) % G handles replacing the last element by 1
ans =
1
1

How to compare two matrices?

My goal is to compare two matrices: A and B in two different files:
function [Result]=test()
A_Mat= load('fileA', 'A')
B_Mat= load('fileB', 'B')
Result= A_Mat == B_Mat
end
The result that I want is a matrix that includes the difference between A and B.
The error that I have is:
error: binary operator '==' not implemented for 'scalar struct' by 'scalar struct' operations
The load function doesn't return what you think it returns. Reading the extensive and easily comprehensible MATLAB documentation always helps.
function Result=test()
load('fileA', 'A');
load('fileB', 'B');
Result = A == B
end
Use the isequal function.
isequal(A,B)
If you simply want the difference between A and B you should first use load as dasdingonesin suggested, and either check for full matrix equality with isequal or elementwise equality with ==. The difference, however, is simply given by - of course:
isequal(A,B); % returns a boolean for full matrix equality
A==B; % returns a logical matrix with element wise equality
A-B; % returns a matrix with differences between the two matrices
Do note that isequal can deal with matrices of unequal size (it will simply return 0), whilst both == and - will crash with the error Matrix dimensions must agree.
First, the operator == does work on matrices, and it returns a logical matrix of true/false (1/0) where the corresponding items are equal or different respectively. From the error you got it seems that you didn't read matrices from the file, but structs, and indeed, == doesn't work for structs.
You can use isequal for both structs and matrices. This function returns only one value - 1 or 0 (true/false).
ADDED
After seeing #dasdingonesin answer, who actually pointed to the exact problem, I just wanted to add that when you write
A_Mat= load('fileA', 'A')
it returns a struct as with the field A.
So:
A_Mat = s.A

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

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.