Get an array of results of a function using as input an array of values (in Matlab) - matlab

I want to get the array of results of a function using as input an array of values. The function receives two variables (x1, x2) and a constant x3, so I'm trying to input all combination of it in a range using mesh.
The result is incorrect, I'm missing something.
Sample:
fun = #(x1,x2,x3) (x2-x1^2)^2+(1-x1)^2 + x3;
x3 = 7;
fun2 = #(x) fun(x(1,1),x(1,2),x3);
x0 = [2 3];
min = fminsearch(fun2, x0);
disp(min);
x = min(1)-10:1:min(1)+10;
y = min(2)-10:1:min(2)+10;
[X,Y] = meshgrid(x,y);
% I'm getting strange values here, like z < 0, how it is possible if everything is squared in the function.
Z = fun(X,Y,x3);

It's important to note that there is a difference between matrix and element-wise operations in MATLAB.
Matrix operations are defined via plain operators, such as *, or ^. So for example, A*B performs a matrix multiplication between A and B.
Element-wise operators make use of the dot . before the operator, i.e., .*, .^, and so on. Thus, A.*B performs an element-wise multiplication of A and B. The end result of this operation is an array of the same size as A and B (whose sizes must be equal), where the jj'th element of the array is equal to A(jj)*B(jj).
Now, consider your definition of fun:
fun = #(x1,x2,x3) (x2-x1^2)^2+(1-x1)^2 + x3;
What happens when MATLAB evaluates this expression is that it applies the matrix operations, such as ^ to the input arrays. However, to obtain your desired result of applying the operation to every individual element in your input arrays x1, x2, you should be using element-wise operations.
A new definition
fun = #(x1,x2,x3) (x2-x1.^2).^2+(1-x1).^2 + x3;
should provide the desired result.

Related

Use of 'ArrayValued' in Matlab numerical integration

Why when performing numerical integration in Matlab with integral does this case need 'ArrayValued' to be set to true:
f = #(x) 5;
integral(f,0,2,'ArrayValued',true)
... while in this case the option isn't needed?:
f = #(x) x;
integral(f,0,2)
From the documentation for integral describing the integrand argument:
For scalar-valued problems, the function y = fun(x) must accept a
vector argument, x, and return a vector result, y. This generally
means that fun must use array operators instead of matrix operators.
For example, use .* (times) rather than * (mtimes). If you set the
'ArrayValued' option to true, then fun must accept a scalar and return
an array of fixed size.
So, a constant function like f = #(x) 5 does not return a result the same size as x if x is a vector. The integral function requires this because under the hood it is vectorized for scalar functions for performance – it actually evaluates the integrand at multiple points simultaneously with a single function call.
You can make your constant function compliant and not require 'ArrayValued' to be true with something like this:
f = #(x) 5+0*x;
integral(f,0,2)

bsxfun doesn't work as I expect on a constant function

In Matlab R2016a, I have a large set of small X-vectors and Y-vectors which are paired (e.g. 10,000 1x3 X-vectors paired with 10,000 1x3 Y vectors). For each {X,Y} pair, I want to calculate a 2-scalar-argument function for every pairwise combination of the elements in X and Y, (so in my example I would get 10,000 3x3 matrices).
I thought I could use bsxfun to perform these calculations, but it doesn't work when I try to do some simple tests. bsxfun(#(x,y) x*y,[1 2],[1 2]') returns:
ans =
1 2
2 4
Which is what I would expect. However, bsxfun(#(x,y) 1,[1 2],[1 2]') returns:
Error using bsxfun
Specified function handle produces invalid output dimensions. The function handle
must be a binary elementwise function.
Which makes no sense. The function handle is a binary elementwise function that always returns the scalar 1, so bsxfun should give the same result as ones(2,2), unless I'm not understanding how bsxfun works.
The inputs to the function handle that are passed to bsxfun are not scalars. In versions prior to R2016b, the inputs are either scalar or they are the same size.
FUNC can also be a handle to any binary element-wise function not listed
above. A binary element-wise function in the form of C = FUNC(A,B)
accepts arrays A and B of arbitrary but equal size and returns output
of the same size. Each element in the output array C is the result
of an operation on the corresponding elements of A and B only. FUNC must
also support scalar expansion, such that if A or B is a scalar, C is the
result of applying the scalar to every element in the other input array.
In releases since R2016b, they do not have to be equal sizes, but should be compatible sizes
In the example you have shown, the first input to the function handle is a scalar and the second is a vector (y) and the function is evaluated for every element of x and the output is expected to be the size of y
In the case you've posted, the call to bsxfun is essentially the equivalent of:
x = [1 2];
y = [1 2].';
yourfunc = #(x,y)x * y;
for k = 1:numel(x)
output(:,k) = yourfunc(x(k), y)
end
If you want to return a 1 for every entry, you need to replace your function with something that yields the appropriately sized output.
bsxfun(#(x,y)ones(max(size(x), size(y))), [1 2], [1 2]')
How you formulate the function handle really depends upon your specific problem

Why does my function return two values when I only return one?

So I'm trying to implement the Simpson method in Matlab, this is my code:
function q = simpson(x,f)
n = size(x);
%subtracting the last value of the x vector with the first one
ba = x(n) - x(1);
%adding all the values of the f vector which are in even places starting from f(2)
a = 2*f(2:2:end-1);
%adding all the values of the f vector which are in odd places starting from 1
b = 4*f(1:2:end-1);
%the result is the Simpson approximation of the values given
q = ((ba)/3*n)*(f(1) + f(n) + a + b);
This is the error I'm getting:
Error using ==> mtimes
Inner matrix dimensions must agree.
For some reason even if I set q to be
q = f(n)
As a result I get:
q =
0 1
Instead of
q =
0
When I set q to be
q = f(1)
I get:
q =
0
q =
0
I can't explain this behavior, that's probably why I get the error mentioned above. So why does q have two values instead of one?
edit: x = linspace(0,pi/2,12);
f = sin(x);
size(x) returns the size of the array. This will be a vector with all the dimensions of the matrix. There must be at least two dimensions.
In your case n=size(x) will give n=[N, 1], not just the length of the array as you desire. This will mean than ba will have 2 elements.
You can fix this be using length(x) which returns the longest dimension rather than size (or numel(x) or size(x, 1) or 2 depending on how x is defined which returns only the numbered dimension).
Also you want to sum over in a and b whereas now you just create an vector with these elements in. try changing it to a=2*sum(f(...)) and similar for b.
The error occurs because you are doing matrix multiplication of two vectors with different dimensions which isn't allowed. If you change the code all the values should be scalars so it should work.
To get the correct answer (3*n) should also be in brackets as matlab doesn't prefer between / and * (http://uk.mathworks.com/help/matlab/matlab_prog/operator-precedence.html). Your version does (ba/3)*n which is wrong.

How to pass the value of an array to a mathematical function in Matlab?

I have a defined mathematical function: f =Inline('x1^2+x2^2+2*x1*x2','x1','x2')
and I have an array that represents the number value of x1 and x2. (e.g. the array is A=[1 2])
I want to automate the process of getting the f(x1,x2), but I couldn't figure out the right way that Matlab can take in the array and assign values to x1 and x2.
What can I do to pass in the array values to the mathematical model and get the function value?
You should be using anonymous functions instead of inline since inline will be removed in a future release of MATLAB.
Example (from the docs):
sqr = #(x) x.^2;
a = sqr(5)
a =
25
In your case:
f = #(x) x(1)^2+x(2)^2+2*x(1)*x(2);
Now it expects x to be a two (or more) value array.
A = [1 2];
f(A) =
9
Note:
I don't have MATLAB on my home computer so I haven't actually tested this but it should get you going in the right direction. Have a look over the docs and you'll be fine.

How do I put in two variables in a matlab function (ERROR: inner matrix dimensions must agree)?

When I try to plot a function h in MATLAB, using a variable omega which is defined as its own function, I get an Inner matrix dimensions must agree, error using _*_ response from the console.
The function works when I use a + between the seperate function-components of h; It does not work when I try multiplying the two inner functions in h, which is, from what I guess, what causes the matrix dim error.
function h = freqp(omega)
k = (1:1024-1);
hh = (1:1024-1);
omega = zeros(length(k),1);
omega = (k-1)*((2*pi)/1024);
hh = 2*exp((-3j)*omega)*cos(omega); % This works for ...omega) + cos(...
% but not for ...omega) * cos(, why?
y = fft(hh);
stem(real(y), omega);
How can I solve this? I read the info on mathworks but it only gives a solution for e.g. loading a file. Any help would be greatly appreciated!
Since Omega is a vector, the addition works. But multiplication of two vectors will result as a matrix. You can modify
hh = 2*exp((-3j)*omega)*cos(omega);
as
hh = 2*exp((-3j)*omega)*(cos(omega))';
or looking for element wise multiplication,
use
hh = 2*exp((-3j)*omega).*cos(omega);
The part exp((-3j)*omega worked fine because -3j is a complex scalar and omega a vector. Thus, MATLAB multiplies each element of omega with -3i. However, that result is a vector itself. Also cos(omega) is a vector, and both are row vectors.
In this case, with two vectors, the *-operator means dot product but that would be calculated between a column vector and a row vector, not two row vectors. So, [1 2 3] * [4 5 6] will raise the same error you are reporting, but [1 2 3] * [4 5 6]' yields 32.
From invoking fft on hh your code looks, however, as if you never intended to calculate a dot product (a scalar) but instead were looking for element-wise multiplication. The operator for element-wise multiplication is .*, such that your expression would be instead
hh = 2*exp((-3j)*omega).*cos(omega);