le function in matlab behaves in this weird fashion. why? - matlab

when entering the logical statement that says
le 4 5
MATLAB returns 1. However if one does,
x=4;
and then
le x 5
MATLAB returns 0. Why is this true and how can I successfully have MATLAB correctly evaluate whether expression is less than or equal to number?

MATLAB has 2 function calling syntaxes, command and function.
Command syntax, used here, treats the inputs as character vectors. To make the logical comparison to a double, MATLAB implicitly converts 'x' to a double, 120, which is its ASCII equivalent. le(120, 5) will obviously evaluate false.
Use function syntax:
>> x = 4; le(x, 5)
ans =
logical
1

You need to use the parenthesis as le is a function with arguments x and 5.
Typing: le(x,5) will return 1.

Related

Evaluate multiple values in a function matlab

I have defined a function in matlab:
function1 = #(x,y,z)[x*y*z,y^2,x+z]
Then in the program I want to writ, I want to evaluate the values of this function for (1,2,3).
Outside the program I can use feval(function1,1,2,3) and this returns
6 4 4.
Now inside my program, I want the input to be like this: output = program(fun, vec), where vec is a vector like [1,2,3].
If I now call: feval(fun,vec) I get the following error message:
Error using #(x,y,z)[x*y*z,y^2,x+z]
Not enough input arguments.
Can someone tell me how I can evaluate the values of my function when the input is a vector instead of three seperate numbers?
Many thanks!
You need a comma-separated list. Define your vector vec as follows:
vec = {1 2 3}
or use
vec = [1 2 3]
vec = num2cell{vec}
and then call feval:
feval(fun,vec{:})
It is actually obsolete to evaluate functions with feval, the following is equivalent:
function1(1,2,3)
function1(vec{:})
As you want to pass the vector vec to your program you need to modify your program to either accepted a various number of inputs with varargin:
program(fun, vec{:))
or you change the evaluation of vec inside your function to vec{:}
You are creating anonymous functions, and they can be used with the following syntax:
myfun= #(x,y,z)([x*y*z,y^2,x+z])
res=myfun(1,2,3);
vect=[1 2 3]
res2=myfun(vect(1),vect(2),vect(3));
In general I would try to avoid using feval.

How to write a inline function which will accept two arguments in MATLAB

I want to write an inline function which will accept two arguments in which one argument is a vector.
>>nCk = #(n,k)(nchoosek(n,k));
>>nCk(3,1:2)
Error using nchoosek (line 29)
The second input has to be a non-negative integer.
How can I make the second argument accepts a vector.
As mentioned, nchoosek only allows integer inputs for the second argument. If you do want to make an inline function, you can fold the loop into a call to arrayfun, however:
nCk = #(n,kVec)arrayfun(#(k)nchoosek(n,k),kVec);
And use like this:
nCk(5,0:5)
ans =
1 5 10 10 5 1
While its probably not what you want, I think this is one situation where I would use a for loop, as nchoosek only accepts an integer for its k value:
nCk = #(n,k)(nchoosek(n,k));
n = 3;
for k = 1:2
disp(nCk(n,k));
end
Though if you do it this way, then the inline statement is likely redundant, so it could be reduced to:
n = 3;
for k = 1:2
disp(nchoosek(n,k));
end
From here ,you can see that you can have as vector the first argument and not the second.
So ,you can use:
nCk = #(k,n)(nchoosek(k,n));
If that helps you of course

How to decipher matlab function syntax ambiguity [duplicate]

This question already has answers here:
What is the # operator (at sign) in MATLAB?
(3 answers)
Closed 9 years ago.
I cannot find this syntax anywhere
y = #(beta, x)x*beta;
where x is some vector or matrix lets say. Is # used to reference another function so you can have more than one externally visiuble function in the same .m file? Sorry I'm new to matlab but can't find this in the documentation
That is the way to define an anonymous function in Matlab. It is basically the same as
function result = y(beta, x)
result = x * beta;
but without needing an m-file or subfunction to define it. They can be constructed within other m-files or even within an expression. Typical use is as a throw-away function inside the call of some complex function that needs a function as one of its inputs, i.e.:
>> arrayfun(#(x) x^2, 1:10)
ans =
1 4 9 16 25 36 49 64 81 100
I personally use them a lot to refactor a list of repetitive statements
a = complex_expression(x, y, z, 1)
b = complex_expression(x, y, z, 3)
c = complex_expression(x, y, z, 8)
into
f = #(n) complex_expression(x, y, z, n)
a = f(1)
b = f(3)
c = f(8)
More info from the Mathworks. They are more or less the same as a lambda expression in Python.
Think of # as anonymous which means an unnamed function (technically, in MATLAB, you must give it a name since you cannot do e.g., (#(x, y) x + y)(1, 2), that name is whatever variable you assign the anonymous function to).
The syntax #(x, y) x + y reads: create an anonymous # function with parameters x and y and return the result of the evaluation of the expression following the next closing parenthesis. In this case, that's the addition of x and y.
One thing that almost no one I know who uses MATLAB uses on a regular basis and instead uses repmat hell instead is bsxfun (it stands for binary singleton expansion).
With the expression bsxfun(#plus, randn(1000, 20), randn(1000, 1)) you essentially repmat the right hand side 20 times to form a new matrix that you then pass to the #plus function handle. You can pass any function around this way. Take a look at cellfun and arrayfun. They are incredibly useful.

Matlab Function with Varying parameters

I need help figuring out how to code the following problem. Any help would be greatly appreciated!
Create a function that will take a vector/array input for x (1 by n) and a scalar input for a, and produce the output defined by the following equation:
y(x,a)=((xsin(ax-2))/(sqrt(1+(ax)^2)
-π ≤ x ≤ π
a={.5 1 1.5 2}
The equation must be vectorized in terms of x and the output from the function is the array y which has the same dimension as the array x.
Write a script that calls this function to compute y(x,a) for the range of x defined above and each value of the parameter a. Results should be stored in a solution matrix using a different row of the solution matrix for each value of a.
So far for my function I have:
function [y] = part1(a,x)
y=((x*sin(a*x-2))/(sqrt(1+(a*x).^2)));
end
I'm not sure how to output this into the solution matrix
For my script I have:
%%
clear,clc
a={0.5 1 1.5 2};
x=-pi:0.1:pi;
for
part1(x,a)
end
I'm getting the following errors when I run this now:
Undefined function 'mtimes' for input arguments of type 'cell'.
Error in part1 (line 4)
y=((x*sin(a*x-2))/(sqrt(1+(a*x).^2)));
Error in labtest2 (line 8)
y(i,:)=part1(x,a(i));
EDIT
I've made some changes and am still getting some errors that I cannot resolve.
Here is my full code for function followed by full code for script:
Function
function [y] = part1(x,a)
nx=numel(x);
na=numel(a);
y=((x.*sin(a.*x-2))./(sqrt(1+(a.*x).^2)));
size(y)=[nx na]
end
Script
%%
clear,clc
a={0.5 1 1.5 2};
x=-pi:0.1:pi;
for i = 1:length(a)
y(i,:)=part1(x,a(i));
end
Errors
Undefined function 'times' for input arguments of type 'cell'.
Error in part1 (line 6)
y=((x.*sin(a.*x-2))./(sqrt(1+(a.*x).^2)));
Error in labtest2 (line 8)
y(i,:)=part1(x,a(i));
The reason you're getting Undefined function 'times' for input arguments of type 'cell' is because your variable a is a cell array. You need to change your assignment of a from
a={0.5 1 1.5 2};
to
a=[0.5 1 1.5 2];
which will make it just a normal array. Alternatively, you need to reference it with cell array notation: a{i} instead of a(i).
You're almost there. Note that you've written
function [y] = part1(a,x)
but you call it in your script as
part1(x,a)
so you should probably correct that.
A few things jump out at me:
You never assign the output of part1(x,a) to anything. You're told that
Results should be stored in a solution matrix using a different row of the solution matrix for each value of a.
What I take this to mean is that the 1st row corresponds to part1() evaluated for the 1st element of a. Since we're operating on x which is a vector, that row will have multiple columns. Your output is indeed a matrix. In your case, length(-pi:0.1:pi) == 63, therefore size(y) == [4 63], where y is your output matrix.
Your for loop is backwards. You're told to accept scalar a and vector x. Therefore, your script should be something like:
a = 0.5:0.5:2;
x = -pi:0.1:pi;
for i = 1:length(a)
y(i,:) = part1(x, a(i));
end
Note the use of length and the : operator. I want to iterate between 1 to length(a) (in this case, length(a) == 4) so that I can use the current a(i) value as an index into my output matrix, y. The : operator in y(i,:) signifies "The ith row and all columns of y will take the value output by part1(x,a(i))."
Your function needs to be changed up for element-by-element operations. Notice that, for instance, x*sin(a*x-2) works for scalar x but not vectors. This is because x is a vector and sin(a*x-2) is also a vector (since the sin call will operate element-by-element and a is a scalar). Trying to multiply two vectors together will result in errors since MATLAB will try to perform a matrix multiplication. Resolve this by replacing * with .*. This way it is unambiguous that you are going to multiply these two vectors element-by-element. You'll also need to change / to ./.
On another note, thank you for attempting to do your homework before asking SO for help. We've been getting a huge influx of questions from students that have made no attempt to do their own work before dumping it on us, so it's refreshing that we regulars of the MATLAB tag get to actual help out instead of telling people to do their own work.
Finally got the whole thing worked out.
Function
function [y] = part1(x,a)
y=((x.*sin(a.*x - 2))./(sqrt(1 + (a.*x).^2)));
end
Script
%%
clear all;
clc;
close all;
x=[-pi:.1:pi];
a=[.5:.5:2];
for i=1:length(a)
y(i,:)=part1(x,a(i));
plot(x,y)
end
Sol=[y]

How can I make XOR work for logical matrix in MATLAB?

>> XOR(X,X)
??? Undefined function or method 'XOR' for input arguments of type 'logical'.
Why XOR can't be used for logical matrix?
And I tried a more simple example:
>> A=[1 0;1 0];
>> B=[1 1;0 0];
>> XOR(A,B)
??? Undefined function or method 'XOR' for input arguments of type 'double'.
How can I properly use XOR?
It works for me.
A=[1 0;1 0];
B=[1 1;0 0];
xor(A,B)
ans =
0 1
1 0
Yet when I try this...
XOR(A,B)
??? Undefined function or method 'XOR' for input arguments of type 'double'.
See the difference. Leave caps off to fix the problem.
I think the ambiguity arises because of a MathWorks convention used in their documentation. When they show the name of a function in their help, they use all caps. For example, here is the help for xor.
>> help xor
XOR Logical EXCLUSIVE OR.
XOR(S,T) is the logical symmetric difference of elements S and T.
The result is logical 1 (TRUE) where either S or T, but not both, is
nonzero. The result is logical 0 (FALSE) where S and T are both zero
or nonzero. S and T must have the same dimensions (or one can be a
scalar).
Even so, when you use the function, you do so with lower case letters in the function name.
How about the following:
C = abs(A-B);
The statement above makes C the XOR of A and B, because xor is true where the entries are different from each other, and 1-0 or 0-1 will give 1 or -1 (and abs of that will give 1), while 0-0 and 1-1 are both 1.
If you really want, you can create an "XOR.m" file with the following definition:
function C=XOR(A,B)
% function C=XOR(A,B)
% INPUTS:
% A - m x n matrix, consisting only of 1s or 0s.
% B - m x n matrix, consisting only of 1s or 0s.
% OUTPUT:
% C - m x n matrix, containing the logical XOR of the elements of A and B
C=abs(A-B)
However, you should keep in mind that function calls in Matlab are horrifically slow, so you might want to just write out the definition that I gave you wherever you happen to need it.
Edit
I did not originally understand your question.... you need to use xor and not XOR, and if it is complaining that your matrices are doubles instead of logicals, then use A==1 and B==1 instead of A and B. Matlab is case sensitive when it comes to variable names and built-in functions such as the xor function.
See this post. C = A~=B