views:

54

answers:

2

I have an expression that gives a matrix and I want to access an element, without creating a temporary variable, something like this cov(M)(1,1). How can I do it?

Thanks!

+5  A: 

It's possible using anonymous functions:

>> f11 = @(M) M(1,1);
>> M = [1 2; 9 4];
>> cov(M)

ans =

    32     8
     8     2

>> f11(cov(M))

ans =

    32

Or for the purists, here it is with no intermediate variables at all:

>> feval(@(M) M(1,1), cov(M))

ans =

    32
Jason S
Nice solution, but in your feval statement consider changing the parameter to a different name than 'M' for clarity.
Geoff
+3  A: 

I have a function like this in my path:

getRegion = @(matrix, rows, cols) matrix(rows,cols);

So that I can then call:

getRegion(cov(M), 1, 1);

It would also work if you wanted a larger region:

getRegion(cov(M), 1:2, 2);
Geoff
nice solution..
Yassin

related questions