Error when calling function
1 view (last 30 days)
Show older comments
Im trying to calculate the 'Zero Crossings' in a sample signal with the below code.
When I try calling the function in the command window using 'zc = ZeroCrossing(t,emg6);' i get an error that says "Attempt to execute SCRIPT ZeroCrossing as a function."
I'd be grateful if someone can shed some insight on this.
Fs=200;
samples=0:2186; %number of data points in matrix
t = samples/Fs; % Time Vector (seconds)
t(:,[1]) = [];
function zc_idx = ZeroCrossing(t,emg6)
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0);
zx = zci(emg6);
zc_idx = zeros(numel(zx),1); % initialise the zero crossing indices
for i = 1:numel(zx)
idx = max([1 zx(i)-1]):min([zx(i)+1 numel(emg6)]);
x_range = t(idx);
y_range = emg6(idx);
zc_idx(i) = interp1( y_range(:), x_range(:), 0, 'linear', 'extrap' ); % returns the approximate zero crossing Indices of argument vector
end
end
0 Comments
Accepted Answer
Geoff Hayes
on 9 Jul 2019
Ejay - see Scripts vs Functions to understand the differences between scripts (which you have written) and function (which you want to write). Since the first line of code (in the above) is neither a comment nor a function signature, then MATLAB assumes that you have written a script. You need to change your code so that the first line is the signature
function zc_idx = ZeroCrossing(t,emg6)
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0);
zx = zci(emg6);
zc_idx = zeros(numel(zx),1); % initialise the zero crossing indices
for i = 1:numel(zx)
idx = max([1 zx(i)-1]):min([zx(i)+1 numel(emg6)]);
x_range = t(idx);
y_range = emg6(idx);
zc_idx(i) = interp1( y_range(:), x_range(:), 0, 'linear', 'extrap' ); % returns the approximate zero crossing Indices of argument vector
end
end
The code
Fs=200;
samples=0:2186; %number of data points in matrix
t = samples/Fs; % Time Vector (seconds)
t(:,[1]) = [];
should be used either in the body of the function or outside of the function (where you need to define the input parameter t).
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!