Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning value to symbol in particular index in symbolic array

I am creating a matrix of symbolic variables (A) and then creating an expression using the variables in this matrix (X). I intend to set the value of the symbol in a particular index in A (for example, in my code I do A(1,1) = 11), and then I want that to be reflected in the expression. However, when I do subs(X), I find that the symbol is not replaced. Is there any way I can achieve this?

Below is what I am trying:

>> A = sym('X', [2 2])

A =

[ X1_1, X1_2]
[ X2_1, X2_2]

>> X = A(1,1)*10 + A(2,2)*11

X =

10*X1_1 + 11*X2_2

>> A(1,1)=11

A =

[   11, X1_2]
[ X2_1, X2_2]

>> subs(X)

ans =

10*X1_1 + 11*X2_2

I could of course do X1_1 = 2. My problem is that this is not amenable to looping. I'd like to set the values in a loop. Obviously A(*,*)=* is amenable to looping. Is there any way to set the value of X1_1 indirectly?

Edit: To achieve this, I can redefine X after setting the value of A(*,*). However this is not an option for me. Defining X is a very costly operation. Doing it multiple times is out of the question for my needs.

like image 420
Abhiram Natarajan Avatar asked Nov 26 '25 08:11

Abhiram Natarajan


2 Answers

Instead of updating an index in A with a value, you can use the symbolic variable in the index of A to substitute that value in X:

>> A = sym('X', [2 2]);
>> X = A(1,1)*10 + A(2,2)*11;
>> X = subs(X, A(1,1), 11)

X =

11*X2_2 + 110

And if you want to do this for all the symbolic variables in A, you don't even have to use a loop. Just one call to subs will work:

>> Avalues = [11 0; 1 10];  % The values corresponding to symbolic variables in A
>> X = subs(X, A, Avalues)

X =

220
like image 166
gnovice Avatar answered Nov 28 '25 02:11

gnovice


Whenever you set the value in a particular index in A, just do X = A(1,1)*10 + A(2,2)*11 one more time, which is amenable to looping.

For example:

A = sym('X', [2 2]);
X = A(1,1)*10 + A(2,2)*11;
A(1,1) = 11;
X = A(1,1)*10 + A(2,2)*11

It will update X:

X =

11*X2_2 + 110

Example for looping:

A = sym('X', [2 2]);
X = A(1,1)*10 + A(2,2)*11;

for i = 1:2
    for j = 1:2
        A(i,j) = 11;
        X = A(1,1)*10 + A(2,2)*11
    end
end

Output:

X =

11*X2_2 + 110


X =

11*X2_2 + 110


X =

11*X2_2 + 110


X =

231
like image 34
Banghua Zhao Avatar answered Nov 28 '25 01:11

Banghua Zhao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!