0

E.g. I have the output of cov(A,B), which is a 2×2 matrix.

I want to select the element in position 2,1 of the matrix.

I can do this by blah = cov(A,B) and then select blah(1,2).

This isn't the most efficient way to do it though, and I'd prefer to do it in one line. Is there a way to do that?

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
InquilineKea
  • 891
  • 4
  • 22
  • 37
  • 2
    I am afraid that the only gain in "efficiency" you may expect here is to remove one LOC. Since `cov` is implemented to return the full matrix, it always will, whether you only need 1 element of it is irrelevant. Note that matlab doesn't make any extra copies just because of the assignment to `blah`. – Marc Claesen Sep 10 '13 at 03:02

2 Answers2

3

You can try using getfield():

getfield(cov(A,B), {1,2})

The performance difference between this and what you have currently will likely be negligible, however. I personally would prefer just using that temporary variable.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 3
    nothing magical here, do `edit getfield` and you'll see it's basically doing: `c={1,2}; x(c{:})` (a feature called comma separated lists) where `x` is the input to the function `x=cov(A,B);`. The way I see, it is just another layer of indirection :) So just use a temporary variable anyway! – Amro Sep 10 '13 at 03:20
1

<stealing brilliance from Amro>

You can also do this:

C = builtin('_paren', cov(A,B), 2, 1);

</stealing brilliance from Amro>

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96