error: undefinded function

1 Ansicht (letzte 30 Tage)
Vaishnavi
Vaishnavi am 19 Mai 2021
Kommentiert: Cris LaPierre am 19 Mai 2021
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();

Antworten (2)

Cris LaPierre
Cris LaPierre am 19 Mai 2021
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 Kommentare
Vaishnavi
Vaishnavi am 19 Mai 2021
Okay.. I tried it's showing error not enough input arguments
Cris LaPierre
Cris LaPierre am 19 Mai 2021
Bearbeitet: Cris LaPierre am 19 Mai 2021
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).

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 19 Mai 2021
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 Kommentar
Cris LaPierre
Cris LaPierre am 19 Mai 2021
I'd argue the if statements are completely unnecessary as well.

Melden Sie sich an, um zu kommentieren.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by