PatStarks
PatStarks

Reputation: 151

Accessing an element that is within a symbolic matrix

I created a 3x3 matrix in MATLAB, where each element of the matrix is an column vector. I am facing some difficulties when I try to access the element of one of the column vectors within the matrix.

syms a b c real

Cube = sym('K', [3,3])

K1_1 = [a; b; c];
K1_2 = [a; b; c];
K1_3 = [a; b; c];
K2_1 = [a; b; c];
K2_2 = [a; b; c];
K2_3 = [a; b; c];
K3_1 = [a; b; c];
K3_2 = [a; b; c];
K3_3 = [a; b; c];

for i = 1:3
    for j = 1:3
        x = Cube(i,j);
        K1_1(3,1) % this does not give an error
        x
        x(3,1) % this gives an error
    end
end

Here is the output of the code above:

Cube =
 
[ K1_1, K1_2, K1_3]
[ K2_1, K2_2, K2_3]
[ K3_1, K3_2, K3_3]
 
 
ans =
 
c
 
 
x =
 
K1_1
 
Error using sub2ind (line 52)
Out of range subscript.

Error in sym/subsref (line 766)
                R_tilde = sub2ind(size(L), Idx.subs{:});

Error in MainSimFile2 (line 22)
        x(3,1)

I successfully set x equal to an element of the matrix which is a column vector. However, I get an error when I try to access an element of the column vector.

How can I set up this matrix?

Upvotes: 0

Views: 102

Answers (1)

Miscellaneous
Miscellaneous

Reputation: 398

As written in the document

Cube = sym('K', [3,3]) creates an 3-by-3 symbolic matrix filled with automatically generated elements. The generated elements do not appear in the MATLAB workspace.

For example,

>> clear all
>> Cube = sym('K', [3,3])
 
Cube =
 
[K1_1, K1_2, K1_3]
[K2_1, K2_2, K2_3]
[K3_1, K3_2, K3_3]
 
>> whos
  Name      Size            Bytes  Class    Attributes

  Cube      3x3                 8  sym

In other words, K1_1 assigned by

K1_1 = [a; b; c];

is not the same K1_1 as either in

Cube =
 
[ K1_1, K1_2, K1_3]
[ K2_1, K2_2, K2_3]
[ K3_1, K3_2, K3_3]

or the one assigned to x by

x = Cube(i,j);

Therefore, this line is actually declaring a new variable K1_1.

K1_1 = [a; b; c];

Also see this answer.

Upvotes: 1

Related Questions