-1
(X^2)(1,2)

X is a square matrix, I just want to get the element from position (1,2) from (X^2) why it does not work?

IKavanagh
  • 6,089
  • 11
  • 42
  • 47
user3495562
  • 335
  • 1
  • 4
  • 16

2 Answers2

4

That's not how Matlab works. You need to assign the result of the matrix multiplication to another matrix, then use it:

A = X^2;
disp(A(1,2));

This is assuming that you really did mean to do matrix multiplication, and not multiply element by element. In the latter case you could have done

disp(X(1,2)^2)

And if you are interested in matrix multiplied result, then

disp(X(1,:)*X(:,2))

will do it, since that is how element (1,2) is calculated. This last solution has the advantage of being very efficient since you only calculate the element you need, instead of computing the entire matrix and throwing N^2-1 elements away just to keep the one. For bigger matrices that will make a difference. Of course it makes the code slightly less readable so I would always recommend writing a comment in your code when you do that - your future self will thank you...

edit take a look at http://www.mathworks.com/matlabcentral/newsreader/view_thread/235798 - that thread broadly agrees with my first statement, although it hints that the syntax you desire might be "part of a future release". But that was said 6 years ago, and it's still not here... It also shows some pretty obscure workarounds; I recommend not going that route (because all the workarounds do is hide the fact that you compute the matrix, then pick just one element. So the workload on the computer is no smaller.)

Floris
  • 45,857
  • 6
  • 70
  • 122
  • I just want (A*A)(1,2), and wonder why matlab gives me an error for my code? – user3495562 Apr 26 '14 at 01:44
  • It gives an error because `(A*A)` is not an object that can be indexed. Just the way the syntax works. But my third option should do what you want, and do it efficiently. – Floris Apr 26 '14 at 01:46
4

Indexing is syntactically not allowed in this case. The simplest workaround is to use getfield

X=magic(5)

X =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

>> getfield(X^2,{1,3})

ans =

   725
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • 1
    +1 for that workaround. Now I see it already appears [here](http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it), but I wasn't aware of it – Luis Mendo Apr 26 '14 at 15:50