Create general symbolic array using MATLAB

64 Views Asked by At

I want to generate array or 1 x M matrix with variables such as (please note that sum goes from i=1 to m-1): enter image description here

Because I want to use Obj later as a general array depends on given M for some optimization purposes. I tried following code in MATLAB but that symbolic L does not support:

function testSymbolic
M=3;
Obj = ones(1,M);
L = sym('L', [1 M]);

tempL = log(1-L);
for m=1:M
    Obj(1,m) =  log((L(m))/(1+L(m))) + sum(tempL(1,1:m-1),2);
end
Obj

However, when I see that following when I run separately:

L = sym('L', [1 3])
L =
[ L1, L2, L3]

L(1)
ans =
L1

can some one please help me to fix this issue?

1

There are 1 best solutions below

4
jolo On

Try

M = 3;
for i = 1:M
    L(i) = sym(['L(' num2str(i) ')'])
end

tempL = log(1-L);
for m=1:M 
Obj(1,m) =  log((L(m))/(1+L(m))) + sum(tempL(1:m-1));
end

This yields e.g.

Obj(3)

ans =

log(L(3)/(L(3) + 1)) + log(1 - L(1)) + log(1 - L(2))

EDIT: Considering you want to calculate the maximum of the Obj-vector I would suggest this:

clear;
M = 3;

L = sym('L', [1 M]);

tempL = log(1-L);
for m=1:M 
    Obj(1,m) =  real(log((L(m))/(1+L(m))) + sum(tempL(1:m-1)));
end

F = matlabFunction(Obj,'vars',{L})
ft = @(v) (max (-F(v)));

Now you can optimize ft.