Info
This question is closed. Reopen it to edit or answer.
Can someone please help me? I keep getting the error message Error: Function definitions are not permitted in this context.
1 view (last 30 days)
Show older comments
function out = RandDir(N)
% Generate a random vector from the set {+/- e_1, +/- e_2,..., +/- e_N}
% where e_i is the ith basis vector. N should be an integer.
I = ceil(2*N*rand);
if rem(I,2) == 1
sgn = -1;
else
sgn = 1;
end
out = zeros(N,1);
out(ceil(I/2)) = sgn*1;
end
0 Comments
Answers (2)
Steven Lord
on 30 Aug 2015
Functions like this may only be defined in function files or in classdef files. You may not define functions in a script file or at the MATLAB command prompt (unless they are anonymous functions.)
0 Comments
Image Analyst
on 30 Aug 2015
You probably have a script with this function defined in it, like a file called test.m that has all of this inside it:
clc; % Clear the command window.
out = RandDir(10); % These two lines of code are just a script, not a function.
function out = RandDir(N)
% Generate a random vector from the set {+/- e_1, +/- e_2,..., +/- e_N}
% where e_i is the ith basis vector. N should be an integer.
I = ceil(2*N*rand);
if rem(I,2) == 1
sgn = -1;
else
sgn = 1;
end
out = zeros(N,1);
out(ceil(I/2)) = sgn*1;
end
Like Steve said, this is the case of a function following a script in the same file. To fix, either put each into its own m-file, or make all code in the file functions, instead of a script and a function. Like if this were all in your test.m, it would be fine:
function test()
clc; % Clear the command window.
out = RandDir(10)
end
function out = RandDir(N)
% Generate a random vector from the set {+/- e_1, +/- e_2,..., +/- e_N}
% where e_i is the ith basis vector. N should be an integer.
I = ceil(2*N*rand);
if rem(I,2) == 1
sgn = -1;
else
sgn = 1;
end
out = zeros(N,1);
out(ceil(I/2)) = sgn*1;
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!