Search code examples
matlabmultidimensional-arrayindexingsymbolic-math

Some problems with accessing individual elements in MATLAB


syms t theta chy sy real;
A = [0 0 0 0; 0 -theta -0.5 0;0 -0.5 0 0;0 0 0 0];
B = [0 theta/2 0.5 0; theta/2 0 0 0;0.5 0 0 0;0 0 0 0];
C = [0 (1-(theta^2))/2 -(theta/2) 0;(1-(theta^2))/2 0 0 0; -(theta/2) 0 0 0;0 0 0 0]; 
D = sym(zeros(4,4));
CS = cat(3,A,B,C,D);

Now when I type

>> CS(:,1,3)

ans =

[               0, 1/2 - theta^2/2, -theta/2, 0]
[ 1/2 - theta^2/2,               0,        0, 0]
[        -theta/2,               0,        0, 0]
[               0,               0,        0, 0]

>> CS(:,:,3)

ans =

[               0, 1/2 - theta^2/2, -theta/2, 0]
[ 1/2 - theta^2/2,               0,        0, 0]
[        -theta/2,               0,        0, 0]
[               0,               0,        0, 0]

which is supposed to be different from CS(1,1,3) and CS(:,1,3).

>> CS(1,1,3)

ans =

[               0, 1/2 - theta^2/2, -theta/2, 0]
[ 1/2 - theta^2/2,               0,        0, 0]
[        -theta/2,               0,        0, 0]
[               0,               0,        0, 0]

All give the same values. How do I access the first value in that particular matrix. I don't want to use the A/B/C matrices.


Solution

  • It is working fine for me (R2011a):

    syms t theta chy sy real;
    A = [0 0 0 0; 0 -theta -0.5 0;0 -0.5 0 0;0 0 0 0];
    B = [0 theta/2 0.5 0; theta/2 0 0 0;0.5 0 0 0;0 0 0 0];
    C = [0 (1-(theta^2))/2 -(theta/2) 0;(1-(theta^2))/2 0 0 0; -(theta/2) 0 0 0;0 0 0 0]; 
    D = sym(zeros(4,4));
    CS = cat(3,A,B,C,D);
    
    >> CS(:,1,3)
    
    ans =
    
                   0
     1/2 - theta^2/2
            -theta/2
                   0
    
    >> CS(:,:,3)
    
    ans =
    
    [               0, 1/2 - theta^2/2, -theta/2, 0]
    [ 1/2 - theta^2/2,               0,        0, 0]
    [        -theta/2,               0,        0, 0]
    [               0,               0,        0, 0]
    
    >> CS(1,1,3)
    
    ans =
    
    0
    

    EDIT: As you see, R2011a gives the expected results. However, I've just checked it on R2010a (the OP's version) and also got your results... so you probably need an upgrade :)