create a polynomial matlab - 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

Related

Creating summation series functions in Matlab with variables for optimization

I have a dataset with 1125 rows and 64 columns. Where first 554 rows belong to one class and the remaining rows belong to the other class. The objective function
is to be minimized in terms of R_1 and R_2 where both are are row vectors(1 x 64). x_i and x_l are the rows from the data matrix. I am trying to minimize this objective function using the optimization toolbox, but I am struggling to get the objective function in the desired form and running into errors. This is how I have coded so far
data = xlsread('data.xlsx');
dat1 = data(1:554,:);
dat2 = data(555:1125,:);
f1 = #(x) 0;
f2 = #(x) 0;
%% for digits labeled 0
for i = 1:554
f1 = #(x) f1 + (dat1(i,:) - x(1)).^2;
end
%% for digits labeled 1
for j = 1:571
f2 = #(x) f2 + (dat2(j,:) - x(2)).^2;
end
%% final objective function
f = #(x) 1/554*f1 + 1/571*f2;
%%
x = fminunc(f);
Please guide me on how to correctly form this type of objective function in Matlab
None of your code makes sense. A few issues
f1 = #(x) 0; and f2 = #(x) 0 define anonymous functions which always return zero. What is the purpose of this?
Every further definition of f1,f2,f is attempting to do arithmetic operations on an anonymous function. It's not clear what you expect this to accomplish.
x = fminunc(f); is missing an argument, it needs an initial guess as well. This isn't just to initialize the algorithm but also so that fminunc knows the dimensions that the input to f should have.
For your case f should be defined so half the values passed to it refer to R1 and the other half refer to R2. For example define
l2_sq = #(x) sum(x.^2,2); % return norm(x,2)^2 for each row of x
f1 = #(R1) sum(l2_sq(bsxfun(#minus, dat1, R1)));
f2 = #(R2) sum(l2_sq(bsxfun(#minus, dat2, R2)));
f3 = #(R1,R2) -10 * norm(R1-R2,1);
f = #(R) f1(R(1:64)) + f2(R(65:128)) + f3(R(1:64), R(65:128));
Since the combined R vector has 128 elements, we need to generate an initial guess that contains 128 elements. In this case we could just use random Gaussian noise
R0 = randn(1,128);
Finally, call fminunc as
Rhat = fminunc(f, R0);
R1 = Rhat(1:64);
R2 = Rhat(65:128);
where R1 and R2 are the optimal values.
Note In MATLAB 2016b and newer, implicit expansion allows you to replace bsxfun(#minus, dat1, R1) with the more efficient dat1 - R1. Similarly for bsxfun(#minus, dat2, R2).

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

Numerical Integral in MatLab using integral command

I am trying to compute the value of this integral using Matlab
Here the other parameters have been defined or computed in the earlier part of the program as follows
N = 2;
sigma = [0.01 0.1];
l = [15];
meu = 4*pi*10^(-7);
f = logspace ( 1, 6, 500);
w=2*pi.*f;
for j = 1 : length(f)
q2(j)= sqrt(sqrt(-1)*2*pi*f(j)*meu*sigma(2));
q1(j)= sqrt(sqrt(-1)*2*pi*f(j)*meu*sigma(1));
C2(j)= 1/(q2(j));
C1(j)= (q1(j)*C2(j) + tanh(q1(j)*l))/(q1(j)*(1+q1(j)*C2(j)*tanh(q1(j)*l)));
Z(j) = sqrt(-1)*2*pi*f(j)*C1(j);
Apprho(j) = meu*(1/(2*pi*f(j))*(abs(Z(j))^2));
Phi(j) = atan(imag(Z(j))/real(Z(j)));
end
%integration part
c1=w./(2*pi);
rho0=1;
fun = #(x) log(Apprho(x)/rho0)/(x.^2-w^2);
c2= integral(fun,0,Inf);
phin=pi/4-c1.*c2;
I am getting an error like this
could anyone help and tell me where i am going wrong.thanks in advance
Define Apprho in a separate *.m function file, instead of storing it in an array:
function [ result ] = Apprho(x)
%
% Calculate f and Z based on input argument x
%
% ...
%
meu = 4*pi*10^(-7);
result = meu*(1/(2*pi*f)*(abs(Z)^2));
end
How you calculate f and Z is up to you.
MATLAB's integral works by calling the function (in this case, Apprho) repeatedly at many different x values. The x values called by integral don't necessarily correspond to the 1: length(f) values used in your original code, which is why you received errors.

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_))

feval with multivariate function and vectorization

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