1

http://www.mathworks.com/matlabcentral/answers/1325-what-is-missing-from-matlab#answer_1931

The basic jist is you can't create a matrix and directly index it.

My question is is there a known work-around for doing something like this?

I have a bunch of functions which operate on 2x1 vectors and I'm using an anonymous function that extracts the second element and does some operation with them.

Something like this:

f = @(theta)(rot_vec(V1,theta)(2) + rot_vec(V2,theta)(2) - rot_vec(V3,theta)(2));

How would I accomplish this same operation in matlab?

helloworld922
  • 10,801
  • 5
  • 48
  • 85

2 Answers2

2

First of all, nothing stops you from defining an anonymous function as a pointer to regular function, with temporary variables.

 V1 = 1;
 V2 = 2;
 V3 = 3;
 f = @(theta)(GetRot(theta,V1,V2,V3);

Note that V1, V2 and V3 are frozen.

 function x = GetRot(theta,V1,V2,V3)
     r1 = rot_vec(V1,theta);
     r2 = rot_vec(V2,theta);
     r3 = rot_vec(V3,theta);
     x = r1(2) + r2(2) + r3(2);
 end

Secondly, as an ugly solution, you might as well use subsref, as it is the official name of () operator.

  m = magic(5);

  m(1:5)(1)  %THIS CAUSES AN ERROR!

  %But how about this one?
  subsref(m(1:5),struct('type','()','subs',{{1,2}}))
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
0

A good work around is to make your own function to do that:

function y=ind(A,i)
  y=A(i)
end

Then you can call it like that:

f = @(theta)(ind(rot_vec(V1,theta),2) + ind(rot_vec(V2,theta),2) - ind(rot_vec(V3,theta),2));

For more complicated cases, I made my own function:

function B = ind( A , varargin )
ii=varargin;
idx=find(cellfun(@isempty,ii));
for id=idx
  ii{id}=1:size(A,id);
end
if iscell(A)
  B=A{ii{:}};
else
  B=A(ii{:});
end
end

You can call it when you have several indices:

ind(foo(b),1:3,1:51: You can also use it with cells, and you replace 1:end by []:

ind(foo(b),1:3,[])

Oli
  • 15,935
  • 7
  • 50
  • 66