Error: Function definition not supported in this context. Create functions in code file.

13 Ansichten (letzte 30 Tage)
Hi I'm new to Matlab, currently using Matlab R2019b.
I was trying to write some coding for median filters, so I found this online and copy pasted it into my Matlab. I tried changing the script into function script, I've tried changing paths, separating the functions. I downloaded the Image processing tools. If i start typing the code without the word 'function', the error will be shown below.
Is there any presettings I need to do? Or anything to do before I type the code in?
This is the code I tried.
function Y = PSMF(x)
x = double(x);
WF = 3; ND = 3;T = 40;a = 65;b = -50;
M = medfilt2(x,[3 3]);
N = abs(x - M);
N(N>T)=0;
N = N ~= 0;
N = double(N);
R = sum(N(:))/(size(x,1) * size(x,2));
if R <= 0.25
WD = 3;
else
WD = 5;
end
TD = a + (b * R);
z = IMPDET(x,ND,WD,TD);
Y = NF(x,z,WF);
%% Impulse Detection
function F1 = IMPDET(x,ND,WD,TD)
X = x;
M = medfilt2(X,[WD WD]);
D = abs(X - M);
F = zeros(size(x));
F(D>=TD)=1;
F1 = F;
X(F1==F)=X(F1==F);
X(F1~=F)=M(F1~=F);
for i = 1:ND-1
M = medfilt2(X,[WD WD]);
F1(abs(X - M)<TD)=F(abs(X - M)<TD);
F1((X - M)>=TD)=1;
X(F1==F)=X(F1==F);
X(F1~=F)=M(F1~=F);
F = F1;
end
return;
%% Noise Filtering
function Y = NF(x,f,WF)
g = f;
Y = x;
Y1 = Y;
g1 = g;
s = sum(g(:));
while s ~= 0
M = medfilt2(Y,[WF WF]);
Y1(g==1)=M(g==1);
g1(Y~=Y1)=0;
Y = Y1;
g = g1;
s1 = sum(g(:));
if s1 ~= s
s = s1;
else
s = 0;
end
end
return;

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 14 Apr. 2020
Chew - in the above code, you are defining three functions (for each, there is the function signature and function body). These functions need to be saved to a file and the file saved somewhere in the MATLAB search path. The function keyword is used to declare a function and is not intended to be used in a function "call". When you want to call a function, you just need to pass in the parameters that this function expects. For the second error message, you haven't defined an x. You need to do this like
>> x = 42; % 42 is just an example - I don't know what the input parameter should be
>> Y = PSMF(x);
or just call the function as
>> Y = PSMF(42);
  2 Kommentare
Chew
Chew am 14 Apr. 2020
Thank you so much! Now I don't get those errors anymore. But can I know how should I implement that part of the code into this?
i=imread('cameraman.tif');
isp=imnoise(i,'salt & pepper',0.1);
figure,imshow(i);
med=medfilt2(isp);
figure,imshow(med);
How can I substitute this medfilt2 into PSMF?
Geoff Hayes
Geoff Hayes am 14 Apr. 2020
What do you want to pass into PSMF? I see (from above) that it callsn medfilt2, so do you just want to do
i=imread('cameraman.tif');
isp=imnoise(i,'salt & pepper',0.1);
figure,imshow(i);
med=PSMF(isp);
figure,imshow(med);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by