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

Torsten
Torsten 2022년 6월 13일
You miss an end statement after the function "chegg".
Jan
Jan 2022년 6월 13일
편집: Jan 2022년 6월 13일

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2022년 6월 13일
편집: Jan 2022년 6월 13일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2022년 6월 13일

편집:

Jan
2022년 6월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by