使用==>时出错fprintf函数未为"sym"输入定义 [英] Error using ==> fprintf Function is not defined for 'sym' inputs

查看:275
本文介绍了使用==>时出错fprintf函数未为"sym"输入定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的MATLAB代码.函数trapezoidal()单独定义,可以正常工作.

This is my MATLAB code. The function trapezoidal() is defined separately and it works fine.

syms x;

f = 10 + 2 * x - 6 * (x^2) + 5 * (x^4);

a = 0;
b = 2;

ans_3points = trapezoidal(f, a, b, 3);
ans_5points = trapezoidal(f, a, b, 5);
ans_7points = trapezoidal(f, a, b, 7);

fprintf('Integral estimate for three equally spaced points is %f.\n', ans_3points);
fprintf('Integral estimate for five equally spaced points is %f.\n', ans_5points);
fprintf('Integral estimate for seven equally spaced points is %f.\n', ans_7points);

actual_ans = int(f, 0, 2);

error_3points = 100 * (actual_ans - ans_3points) / actual_ans;
error_5points = 100 * (actual_ans - ans_5points) / actual_ans;
error_7points = 100 * (actual_ans - ans_7points) / actual_ans;

fprintf('Percentage relative error for three equally spaced points is %f.\n', error_3points);
fprintf('Percentage relative error for five equally spaced points is %f.\n', error_5points);
fprintf('Percentage relative error for seven equally spaced points is %f.\n', error_7points);

但是这在打印error_3points的行上给出了以下错误: ???使用==> fprintf时出错 没有为"sym"输入定义功能.

But this gives the following error at the line that prints error_3points: ??? Error using ==> fprintf Function is not defined for 'sym' inputs.

我没有在fprintf()中输入任何'sym'输入,对吗? ans_3points,ans_5points,ans_7points可以毫无问题地打印出来. 这些错误是经过计算的,但是当我检查它们时,它们被显示为分数. 这段代码到底是什么问题?我真的不知道. 谢谢.

I haven't put any 'sym' inputs in fprintf() have I? ans_3points, ans_5points, ans_7points are printed without any problem. The errors are calculated but when I checked they were displayed as fractions. What exactly is the problem in this code? I really can't figure it out. Thank you.

功能trapezoidal:

function l = trapezoidal(f, a, b, n)

N = n - 1;  % N - the number of segmets

syms x;

series_sum = 0;

for i = (0 : (N - 1))
    series_sum = series_sum + subs(f, x, xterm(i, a, b, n)) + subs(f, x, xterm((i + 1), a, b, n));
end

l = series_sum * (b - a) / (2 * N);

推荐答案

问题出在使用函数int

actual_ans = int(f, 0, 2);

`actual_ans'仍然是一个符号变量,即使它是一个常量也是如此.您可以使用

`actual_ans' is still a symbolic variable, even if it is a constant. You can translate it into a numeric variable with

actual_ans = double(actual_ans);

这篇关于使用==>时出错fprintf函数未为"sym"输入定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆