error: undefinded function

7 次查看(过去 30 天)
Vaishnavi
Vaishnavi 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