2

Say I have a vector like [10,3,4], is there a way to get, for instance, the second element directly? Something like:

[10,3,4](2)

Also, if I have a cell of anonymous functions,such as:

funcs = {@(s) s^2 , @(s) s+5},

is there a way to access them in a way like:

funcs{2}(s)

(Edit: funcs{2}(s) works. It turns out the error I got was because of something else!) What I want to do is to save the gradient of a function in a cell like $gradr$ and then be able to get its dot product with another vector. Something lik:

dot([gradr{1}(s),gradr{2}(s)],n)

I cannot assign each component a different name since I'll be using the numbering later.

Thank you in advance.

Edit: the answer to the first part of my question can be found here.

0

3 Answers 3

2

i) No, not really. You need to put [10, 3, 4] into a variable a and then get the second element a(2). (You can do it, but it's not worth it).

ii) Yes: just use funcs{2}(2), or feval(funcs{2}, 2).

iii) You can try something like:

>> inarg = 1;
>> cellfun(@(x)feval(x,inarg),funcs)
ans =
     1     6
3
  • So you can use funcs{2}(s) directly! Nice
    – Luis Mendo
    Mar 12, 2015 at 11:04
  • @LuisMendo, yes, no need for feval there. I just put the possibility in as a lead-in to my answer to part three. Mar 12, 2015 at 11:06
  • I gave funcs{2}(2) another try and the error I got was because of something else! It works fine now,thanks.
    – secluded
    Mar 12, 2015 at 11:07
1

For the first part: quoting gnovice's words, it's actually possible, but ugly. Perhaps the easiest way (described in one of the answers to the linked question) is to (ab)use getfield:

>> getfield([3 4 5],{2})
ans =
    4

For the second part: you can use feval:

>> funcs = {@(s) s^2, @(s) s+5};
>> s = 3;
>> feval(funcs{2}, s)
ans =
     8

or see Sam Robert's answer.

0

You could use ans(2) if you're going to call the vector temporarily, otherwise, you'll better affect it to a variable.

>> [10,3,4]

ans =

    10     3     4

>> ans(2)

ans =

     3
1
  • 2
    Actually, by not putting an assignment operator there you assign it to the variable ans. Depending on ans can be acceptable for a quick calculation on the command line, but I would recommend strongly against using anything like this in a normal function or script. Mar 12, 2015 at 11:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.