feval with multivariate function and vectorization - matlab

I need feval called with a bivariate function f and two vectors v1 and v2 (let us say that v1 are the x's and v2 the y's) to return a vector z=[f(v1(1),v2(1)) ... f(v1(n),v2(n)].
How can I do that ?
The following example does not work:
function z = f(x,y)
if x>0.5
z=x+y;
else
z=x+2*y;
end
end
indeed,
feval(f,[0.4 2 3],[4 5 6])
returns: [8.4 12 15]
instead of [8.4 7 9].
What is the correct syntax ?

The if condition doesn't work element-wise, as you seem to expect. Rather, the if branch is entered only if all the elements in the expression (x>0.5 in your case) evaluate to true.
To achieve what you want, change your function to
function z = f(x,y)
ind = x>.5;
z(ind) = x(ind) + y(ind);
z(~ind) = x(~ind) + 2*y(~ind);
end
Note that the logical index ind takes the place of your if.
For your particular function, the code could be simplified to
function z = f(x,y)
z = x + y + (x<=.5).*y;
end

Related

Create a variable number of terms in an anonymous function that outputs a vector

I'd like to create an anonymous function that does something like this:
n = 5;
x = linspace(-4,4,1000);
f = #(x,a,b,n) a(1)*exp(b(1)^2*x.^2) + a(2)*exp(b(2)^2*x.^2) + ... a(n)*exp(b(n)^2*x.^2);
I can do this as such, without passing explicit parameter n:
f1 = #(x,a,b) a(1)*exp(-b(1)^2*x.^2);
for j = 2:n
f1 = #(x,a,b) f1(x,a,b) + a(j)*exp(b(j)^2*x.^2);
end
but it seems, well, kind of hacky. Does someone have a better solution for this? I'd like to know how someone else would treat this.
Your hacky solution is definitely not the best, as recursive function calls in MATLAB are not very efficient, and you can quickly run into the maximum recursion depth (500 by default).
You can introduce a new dimension along which you can sum up your arrays a and b. Assuming that x, a and b are row vectors:
f = #(x,a,b,n) a(1:n)*exp((b(1:n).^2).'*x.^2)
This will use the first dimension as summing dimension: (b(1:n).^2).' is a column vector, which produces a matrix when multiplied by x (this is a dyadic product, to be precise). The resulting n * length(x) matrix can be multiplied by a(1:n), since the latter is a matrix of size [1,n]. This vector-matrix product will also perform the summation for us.
Mini-proof:
n = 5;
x = linspace(-4,4,1000);
a = rand(1,10);
b = rand(1,10);
y = 0;
for k=1:n
y = y + a(k)*exp(b(k)^2*x.^2);
end
y2 = a(1:n)*exp((b(1:n).^2).'*x.^2); %'
all(abs(y-y2))<1e-10
The last command returns 1, so the two are essentially identical.

Algorithm to find a value that gives the minimum output for two or equations

Suppose I have two equations with only one variable (free parameter) x and that k1 and k2 are constants. I would like to solve for:
f(x) + k1 = 0
&
g(x) + k2 = 0
...
h(x) + kn = 0
Of course there is no value of x that satisfies all of these equations. I basically would like the value of x that minimizes the output of each of these equations.
'solve' in matlab looks for an exact answer and returns an error, here's an example to demonstrate:
syms x
solution = solve(0.5*(x-k1)/sqrt(2) == 0, 0.5*(x-k2)/sqrt(2) == 0);
You can try using Unconstrained Optimization method such as fminsearch, for example:
h=#(x) x^2;
g=#(x) x^3;
k1=2;
k2=4;
inital_guess=3;
f = #(x) sum(abs([h(x)+k1; g(x)+k2]));
[x,fval] = fminsearch(f,inital_guess)
Note that I represent both eq in matrix form, and the minimization is by looking at the sum of their absolute values.
For the values I entered the value of x that minmize these eq is given by the output x = -1.5874

Plotting function in octave

I have a simple function I wrote:
function f = G(s)
f = 16/(s.^2+3*s+16)
endfunction
I want to plot this transfer function from s = 0 to 4 with a step of 0.01. For some reason I can't get it to work. I am getting nonconformant arguments errors. I am new to octave.
If it is a transfer function, then you want to use the control package to get a Bode plot rather than plotting it as a function, which don't really make sense (s being complex):
>> G = tf(16,[1 3 16])
Transfer function 'G' from input 'u1' to output ...
16
y1: --------------
s^2 + 3 s + 16
Continuous-time model.
>> bode(G)
which gives
A dot was missing. It is mandatory when you want an element by element operation like (./).
See the difference between x / y and x ./ y in https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html.
function G = G(s)
G = 16./(s.^2+3*s+16);
endfunction
s_ = 0:0.01:4;
plot(s_, G(s_))

create a polynomial matlab

I have got vector of coefficients v=[v1, v2, v3] (added by user).
I want to create a polynomial in a function. I would like to have a function fun(x), which solution will be my polynomial. After that I want to have a graph of this polynomial.
This is my idea but it doesn't work. Could you have any ideas how to improve it?
function [v] = createPolynomial(x)
r = length(v);
fun=0;
for i=r:1
fun=fun+v(i)*x.^(r-1);
end
You're pretty close! Is this what you want?
function f = createPoly(v,x)
n = length(v);
f = 0;
for ii = 1:n
f = f + v(ii)*x.^(n-ii+1);
end
end
f = createPoly([1 2 3 5],4)
f =
113
%% (1*4^3) + (2*4^2) + (3*4^1) + (5*4^0) = 113
Some errors in your code:
function [v] = createPolynomial(x)
As I understand it, you want both v and x as inputs to your function, and get a value back. Then you must do function value = createPolynomial(v, x), where valuewill be the output variable.
fun=fun+v(i)*x.^(r-1);
I guess this is just a typo, but .^r-1 is a constant value. You probably want the exponent to go from n, n-1, ... 1, 0 In that case you want r-i. And if I don't point it out, someone else will definitely do: Using i as a variable in MATLAB is not good practice if you are sometimes dealing with complex numbers.
And I guess you know this, but I'll say it anyway: You m-file must have the same name as you function.
If you want to input x as a vector, you must initialize f as a vector having the same length as x. That is:
f = zeros(1,length(x));
Now, you can do:
f = createPoly([1 2 3 5],1:5)
f =
11
27
59
113
195
you define coefficients in the following form of variable p
% example :
p =[ 2 1 3] % coefficients
x=0:0.2:5; % values at which it is to be evaluated
y=polyval(p, x);
plot(x,y)
polyval is provided in standard matlab, it evaluates the polynomial. see help polyval

Sending a function into a matlab function

I'm trying build a matlab function that will evaluate a function and vector that are sent in as parameters. I'm having a hard time trying to figure out how to send in the function so that it can be evaluated in the matlab function. I figured out how to do it without the function but I'm a little lost trying to evaluate it within a matlab function. Below is my code...
This is what I'm trying to do...
x = [x1 x2]';
f = x(x1)^2 + 2 * (x2)^2
x = [5 10];
f = (5)^2 + 2 * (10)^2 % which I would like to return 225, not a column vector
This is what I have and what I have tried...
x = [5 10]';
% without using a matlab function
% k = 1
% f = x(k)^2 + 2 * x(k + 1)^2; % returns the correct answer of 225
f = x^2 + 2 * x^2 % complains about the scalar 2
f = x.^2 + 2 * x.^2 % returns a column vector [75; 300]
function [value] = evalFunction(f,x)
value = f(x);
I've tried...
f = #(x) x.^2 + 2 * (x+1).^2;
value = evalFunction(#f,x) %Error: "f" was previously used as a variable
So I tried...
f = #(x) x.^2 + 2 * (x+1).^2;
value = evalFunction(f,x) %value = [97;342]
I'm new to matlab so any help is appreciated. I've been doing some research and found some stuff here on stackoverflow but can't seem to get it to work. I've seen there are other ways to do this, but I will eventually be adding more code to the matlab evalFunction function so I'd like to do it this way. Thanks!
Anonymous functions and function handles plus array indexing. Taking x as a 2-element vector, define and use your function like:
f = #(x) x(1).^2 + 2 * x(2).^2;
value = evalFunction(f,x) % but you can just do f(x) if that is all you need
However, if evalFunction does nothing other than evaluate f at x, then you don't need it at all. Just do f(x).
Alternately,
f = #(x1,x2) x1.^2 + 2*x2.^2;
value = evalFunction(f,x1,x2); % here your function will call it by f(x1,x2)
You are probably coming at this from a C background - in Matlab, x+1 is the entire vector x with 1 added - not the element offset by 1.
The function you need is
f = #(x)x(1).^2 + 2 * (x(2)).^2;
or, to be a little more "matlab-like":
f = #(x) [1 2] * x(1:2)'.^2;
Which performs the element-wise square of the first two elements of x as a column vector, and then does the matrix multiplication with [1 2], resulting in
1 * x(1) .^2 + 2 * x(2) .^2;
Which seems to be what you were asking for.
caveat: did not have opportunity to test this...