I had an error when İ run the code

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

You miss an end statement after the function "chegg".

Sign in to comment.

Answers (1)

Jan
Jan on 13 Jun 2022
Edited: Jan on 13 Jun 2022
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

Asked:

on 13 Jun 2022

Edited:

Jan
on 13 Jun 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!