I had an error when İ run the code
Show older comments
hey guys , ı am trying to run this code (İN MATLAB ) but it gives me error , can you explain and solve it to me ??
urgently !!!
function[r]=chegg(x)
r=[];
r=[r 1];
curr=x(1);
for i=2:1:length(x)
if(curr==x(i))
r= [r r(i-1)+1];
else
curr=x(i);
r=[r 1];
end
end
function[r]=chegg(x)
↑
Error: Function definition are not supported in this context. Functions can only be created as local or nested functions in code files.
2 Comments
Torsten
on 13 Jun 2022
You miss an end statement after the function "chegg".
Avoid the term "urgently" - see https://www.mathworks.com/matlabcentral/answers/29922-why-your-question-is-not-urgent-or-an-emergency
Answers (1)
The error message is clear already:
Functions can only be created as local or nested functions in code files.
So where did you create this function? In the command window?
By the way, simplify:
r=[];
r=[r 1];
by
r = 1;
A simpler version of the complete function:
function r = chegg(x)
r = ones(size(x));
for i = 2:length(x)
if x(i-1) == x(i)
r(i) = r(i-1) + 1;
end
end
end
You can even omit the IF command:
function r = chegg(x)
r = ones(size(x));
for i = 2:length(x)
r(i) = (x(i-1) == x(i)) * r(i-1) + 1;
end
end
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!