How do I get my function to return a numerical value?

조회 수: 25 (최근 30일)
Valielza O'Keefe
Valielza O'Keefe 2020년 2월 19일
댓글: Valielza O'Keefe 2020년 2월 19일
Hi, I'm working on this for a MATLAB course at my university. Below is my assignment.
Here is the code I have so far, which was mostly provided by the instructor as a jumping-off point for us:
function [solnx] = HW5VJO(n,a)
F = @(x) 1;
for t = 1:n
M = @(x) 1;
for k = 1:(n-1)
M = @(x) M(x)*(x-k*a);
end
solnx = @(x) F(x)+M(x)
end
end
We also have a separate call file (script) for the function as follows:
%Call file for HW 5
clear; clc;
x = 5;
n = 3;
a = 1;
solnx = HW5VJO(n,a)
Not everything is figured out. For example, I have not figured out how to add the coefficient for every term in the function. However, I'd really appreciate some help as MATLAB does not return any numerical values at all, making it very difficult for me to verify whether it's working as intended. I just get the following message repeated several times:
solnx =
function_handle with value:
@(x)F(x)+M(x)
Any suggestions? Do I simply have to go and sub the values for F(x) and M(x) manually? Any other help regarding the assignment would be fantastic. I'm absolutely stuck.

채택된 답변

M
M 2020년 2월 19일
The function HW5VJ0 returns a function handle. To get a numerical value, you have to call it with the specified value of x:
x = 5;
n = 3;
a = 1;
solnx = HW5VJO(n,a);
solnx(5)
ans =
13
To know why you d'ont get the desired value 45, you have to look into the function definition and change it accordingly.
If you don't want
solnx =
function_handle with value:
@(x)F(x)+M(x)
to be displayed at every iteration loop, simply add ; at the end of the line:
solnx = @(x) F(x)+M(x) ;
  댓글 수: 1
Valielza O'Keefe
Valielza O'Keefe 2020년 2월 19일
Ahh, thank you so much! This makes it much easier for me to now evaluate my function files. Thank you again!

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

추가 답변 (0개)

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by