0

It is a very simple problem, though I do not know how to deal with it.

I defined a function f(x,y) which will return a, say, 2*2 matrix. I want to define a new function g whose value is the (1,1) element of f(x,y). I naively tried g=@(x,y)(f(x,y))(1,1), which of course failed . Please help me!

Tom
  • 103
  • 2
  • The easiest way to get the (1,1) element of a matrix is just to call `f(1,1)`. A function isn't really needed. – eigenchris Dec 05 '14 at 14:56
  • But `f(1,1)` will return a 2*2 matrix. – Tom Dec 05 '14 at 14:59
  • Sorry, I realize you called your function `f`. If you have a matrix `M`, you can get its `(1,1)` element using `M(1,1)`. – eigenchris Dec 05 '14 at 15:02
  • 1
    Have a look at [this question](http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it). There several possible solutions are described. – hbaderts Dec 05 '14 at 15:06

2 Answers2

1

You can use :)

g = @(x,y)([1 0] * f(x,y) * [1 0]')
Kostya
  • 1,552
  • 1
  • 10
  • 16
1

You can use the function getfield

Let's define f(x,y) to return a 2x2 matrix

f = @(x,y) [1*x 2*y;3*x 4*y].^2 ;

Then let's define a function g11(x,y) which return the element {1,1} of f(x,y). (and an extra function g21 which return the {2,1} element)

g11 = @(x,y) getfield( f(x,y) , {1,1} ) ;
g21 = @(x,y) getfield( f(x,y) , {2,1} ) ;

And now:

>> f(3,4)
ans =
     9    64
    81   256

>> g11(3,4)
ans =
     9

>> g21(3,4)
ans =
    81

For more fancy usage of field assignment without temporary variable, read all the nice answers in this question

Community
  • 1
  • 1
Hoki
  • 11,637
  • 1
  • 24
  • 43