0

I'd like to know MATLAB's equivalent to Java's {} for delimiting code blocks. It seems that it would be simple to find out such a thing, but it is hard to search {} on Google, so I turn to StackOverflow. Thanks for the help!

EDIT: My goal is to define a multi-line anonymous function.

astay13
  • 6,857
  • 10
  • 41
  • 56
  • 1
    What is it you want to achieve? Local scope variables, code folding for easy editing? – angainor Sep 25 '12 at 17:45
  • Already asked: http://stackoverflow.com/questions/558478/how-to-execute-multiple-statements-in-a-matlab-anonymous-function – Oli Sep 25 '12 at 18:12

2 Answers2

2

You can define a sub-function in the same file to do that:

function y=foo()
  y=1;
  bar(y)
end

function z=bar(y)
  x=2*y; % x stays local
  z=2*x;
end
Oli
  • 15,935
  • 7
  • 50
  • 66
  • The problem with this on the other hand is that you can not define functions in simple scripts. That's why foo needs to be a function. – angainor Sep 25 '12 at 18:06
2

You can use ... to continue lines. So to make a multi-line anonymous function:

fun=@(x)(...
    x.^2+...
    x+...
    1);

fun(1:10)

ans =

 3     7    13    21    31    43    57    73    91   111

If on the other hand you want to have multiple statements in an anonymous function, it is not possible. See e.g. this other SO post.

Community
  • 1
  • 1
angainor
  • 11,760
  • 2
  • 36
  • 56
  • lol, that actually is multi-line. But he meant anonymous function with serveral instructions (e.g x=2;y=3;z=x*y;). – Oli Sep 25 '12 at 18:04
  • @Oli well, I just answered the question :) Thats why I asked to make it more precise.. – angainor Sep 25 '12 at 18:05