error: undefinded function

조회 수: 2 (최근 30일)
Vaishnavi
Vaishnavi 2021년 5월 19일
댓글: Cris LaPierre 2021년 5월 19일
a = ['img1.PNG','img2.PNG','img3.PNG'];
next();
pre();
function next()
i = 2;
if( i == 3)
cap = imread(a(3));
imshow(cap);
else
i = i + 1;
cap = imread(a(i));
imshow(cap);
end
end
function pre()
i = 2;
if (i == 1)
cap = imread(a(1));
imshow(cap);
else
i = i - 1;
cap = imread(a(i));
imshow(cap);
end
end
error:
>> code
Unrecognized function or variable 'a'.
Error in code>next (line 11)
cap = imread(a(i));
Error in code (line 2)
next();

답변 (2개)

Cris LaPierre
Cris LaPierre 2021년 5월 19일
You need to keep in mind what workspace your variables are in. See the Base and Function Workspace page.
You define variable a in your base workspace, but do not pass it into your function workspace. Since a does not exist as a variable in next(), MATLAB assumes it must be a function. When it can't find a function, it throws the error you are seeing.
Here's an example from that page.
z = 1:99;
ave = average(z)
ave = 50
function ave = average(x)
ave = sum(x(:))/numel(x);
end
  댓글 수: 4
Vaishnavi
Vaishnavi 2021년 5월 19일
Okay.. I tried it's showing error not enough input arguments
Cris LaPierre
Cris LaPierre 2021년 5월 19일
편집: Cris LaPierre 2021년 5월 19일
You are not passing your input to your function when you call it. Let's take a break from your code and look at the the example I shared. It's taken from here. Try to implement one of these examples. What is different between how they call the function and how your code does it?
Again, you'll find this page helpful: Declare function input(s) and output(s).

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


Image Analyst
Image Analyst 2021년 5월 19일
Dolly, you need to make (the badly-named) "a" a string array, not a character array. Or a cell array. Then you need to pass "a" into the functions.
You also need to declare "i" persistent if you want to retain its value inside the function. Or else pass i into and out of the functions. And of course there are lots of other things you could do to make the code more robust, like adding comments, choosing more descriptive variable names, using the fullfile() function, checking if the file exists first with isfile() so it doesn't crash if the file does not exist, etc. etc.
a = ["img1.PNG", "img2.PNG", "img3.PNG"]
next(a);
pre(a);
fprintf('Done running %s.m\n', mfilename);
function next(a)
i = 2;
if( i == 3)
cap = imread(a(3));
imshow(cap);
else
i = i + 1;
cap = imread(a(i));
imshow(cap);
end
end
function pre(a)
i = 2;
if (i == 1)
cap = imread(a(1));
imshow(cap);
else
i = i - 1;
cap = imread(a(i));
imshow(cap);
end
end
  댓글 수: 1
Cris LaPierre
Cris LaPierre 2021년 5월 19일
I'd argue the if statements are completely unnecessary as well.

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

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by