0

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?

1 Answer 1

1

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.

2
  • ok thanks! Yes I understand that x is assigned to a new value. In that case what is the best way to create a matrix of vectors?
    – PatStarks
    Nov 17, 2021 at 16:26
  • 1
    It depends on what you are going to use the matrix. You have two sets of symbols here, namely K and a, b, c. Do you really need all of them? Nov 18, 2021 at 6:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.