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 comentarios

Torsten
Torsten el 13 de Jun. de 2022
You miss an end statement after the function "chegg".
Jan
Jan el 13 de Jun. de 2022
Editada: Jan el 13 de Jun. de 2022

Iniciar sesión para comentar.

Respuestas (1)

Jan
Jan el 13 de Jun. de 2022
Editada: Jan el 13 de Jun. de 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

Categorías

Etiquetas

Preguntada:

el 13 de Jun. de 2022

Editada:

Jan
el 13 de Jun. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by