How can I create this function?

1 view (last 30 days)
I need help writing a function that will carry out the following:
y(x) = Bj*Cj(x)*aj
where Cj = diag[exp(im*k*x),exp(-im*k*x)]
Bj and aj are not dependent on x
How can I write code for this in MATLAB?

Accepted Answer

CARLOS RIASCOS
CARLOS RIASCOS on 4 Apr 2018
I did this for you, I hope it serves you.
% Definition of constants:
k=2;
Bj=[1 2; 3 4]; %In this case Bj is a matrix of size 2x2,
%of real numbers,you can modify this.
aj=[1; 1]; %In this case aj is a vectorof size 2x1,
%of real numbers,you can modify this.
%This is the definition of your function:
Y=@(x)(Bj*diag([exp(k*x(1)*1i),exp(-k*x(2)*1i)])*aj);
%To test, if x is a constant, define the vector only with
% that constant(expl: x = 5, so here you define x = [5 5]); if x is
%a vector of variables, you define it as it is here in the code:
x=[1 2];
Y=Y(x);
disp(Y) %Check the value in Command Window.
  1 Comment
Amanda Lococo
Amanda Lococo on 4 Apr 2018
Thank you! Is there a way I can use one specific value of Y(x) in a formula? For example, Bj and aj are also functions so I have written this so far, but a (when j is not 0) needs to be equal to inv(Cj(x))*inv(Bj)*T*B(1)*a(1). When I display B(1) it gives me back a value of one, which isn't right so I'm not sure how to code it.
for j = 1:layers
B = @(j)([1 1; im*Z(j,1) -im*Z(j,1)]);
B = B(j);
C = @(j)([exp(im*k(j,1)*x(j,1)) 0; 0 exp(-im*k(j,1)*x(j,1))]);
C = C(j);
if j == 1
a = @(j)(inv(B)*V(:,1));
a = a(j);
else
a = inv(C)*inv(B)*T* %this is where I need to add

Sign in to comment.

More Answers (1)

CARLOS RIASCOS
CARLOS RIASCOS on 5 Apr 2018
This code should return in the variables: B_mtrx_a, C_mtrx_a, a_; a "history" of calculations of matrix B, C and vector a. Observe the command window to show the calculations for each iteration of the for loop.
clear all
im=1i; %Imaginary part
% You should modify these variables:
Z = [1;2];
k = [1;2];
X = [1;2];
V = ones(2);
T = ones(2);
% Definition of the functions:
B = @(x)([1 1; im*Z(x,1) -im*Z(x,1)]);
C = @(x)([exp(im*k(x,1)*X(x,1)) 0; 0 exp(-im*k(x,1)*X(x,1))]);
layers = 2;
%pre-allocation, to save the history of calculations.
B_mtrx_a = [];
C_mtrx_a = [];
a_a = [];
for j = 1:layers
B_mtrx = B(j); C_mtrx = C(j);
disp('B:')
disp(B_mtrx)
disp('C:')
disp(C_mtrx)
B_mtrx_a = [B_mtrx_a B(j)];
C_mtrx_a = [C_mtrx_a C(j)];
if j == 1
a = inv(B_mtrx)*V(:,1);
a_a = [a_a a];
alfa = B_mtrx; beta = a; %You save the specific
%values in auxiliary variables.
else
a = inv(C_mtrx)*inv(B_mtrx)*T*alfa*beta;
a_a = [a_a a];
end
disp('a:')
disp(a)
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!