Error with function handle syntax

조회 수: 3 (최근 30일)
Suhas Subramanya Hoysala
Suhas Subramanya Hoysala 2019년 11월 4일
댓글: Steven Lord 2019년 11월 4일
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
Steven Lord
Steven Lord 2019년 11월 4일
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!

댓글을 달려면 로그인하십시오.

답변 (1개)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 4일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by