Error with function handle syntax
2 views (last 30 days)
Show older comments
Hello,
I have been trying to define a function handle and I keep getting an unspecified error. I have been trying to debug this issue to no avail. Here is my code:
clc;
clear;
n=100;
x = rand(n,1)*10;
x = sort(x);
f = @(u)exp(-u./2)*sin(2*u./1);
y = f(x);
y_perturb = zeros(n,1);
eps = 10^(-2);
for i = 1:n
y_perturb(i) = y(i)+rand()*eps;
end
1 Comment
Steven Lord
on 4 Nov 2019
JESUS DAVID ARIZA ROYETH has correctly identified the reason this wasn't working. You need to use array multiplication (.*) instead of matrix multiplication (*) between your calls to exp and sin in your f function. I have several other comments that I want to add, most related to your code and one related to your post.
clc;
clear;
Use these two functions sparingly. Be especially careful about using clear. Not only does it clear variables from the workspace it also clears breakpoints which are a key tool in debugging your code.
eps = 10^(-2);
for i = 1:n
y_perturb(i) = y(i)+rand()*eps;
end
This loop is unnecessary if you take advantage of vector operations in MATLAB. This code calls the rand function n times, each to generate one pseudorandom number, calls the * operator n times, each time to multiply two scalars, and calls the + operator n times, each time to add two scalars. Instead I recommend generating n pseudorandom numbers in one call and performing the addition and multiplication on vectors of data in one call.
y_perturb = y + rand(size(y))*eps;
Also regarding this section of your code, the identifier eps already has a meaning in MATLAB so consider using a different variable name.
Finally, about this post, when you experience an error please post the full text of the error message (all the text displayed in red) in your Answers post along with the source code. Often the full text of the error includes information that will help readers of your question focus on the line or lines of your code where the error occurs. Sometimes the error message text will allow experienced readers to guess / know the cause of the problem without even needing to look at your code!
Answers (1)
JESUS DAVID ARIZA ROYETH
on 4 Nov 2019
solution:
clc;
clear;
n=100;
x = rand(n,1)*10;
x = sort(x);
f = @(u)exp(-u./2).*sin(2.*u./1);
y = f(x);
y_perturb = zeros(n,1);
eps = 10^(-2);
for i = 1:n
y_perturb(i) = y(i)+rand()*eps;
end
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!