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

26 vues (au cours des 30 derniers jours)
Valielza O'Keefe
Valielza O'Keefe le 19 Fév 2020
Commenté : Valielza O'Keefe le 19 Fév 2020
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.

Réponse acceptée

M
M le 19 Fév 2020
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 commentaire
Valielza O'Keefe
Valielza O'Keefe le 19 Fév 2020
Ahh, thank you so much! This makes it much easier for me to now evaluate my function files. Thank you again!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by