How do I solve "Conversion to logical from sym is not possible" error on line 26

35 次查看(过去 30 天)
clear; clc;
sym h;
f = @(x) 10*pi*h^2-((pi*h^3)/3)-1000;
F = @(x) 20*pi*h-pi*h^2; %calculated by hand
n = 6;
eps = 1*10^-(n+1); %epsilon value
h0 = 6;
for i = 1:20
f0 = vpa(subs('f','h','h0'));
f0_prime = vpa(subs('F','h','h0'));
Y = (h0-f0)/f0_prime; % The Formula
error = abs(Y-h0);
if error < eps %checking the error value after each iteration <===== LINE 26
break
end
h0 = Y;
end
Y = Y - rem(Y,10^-n)

回答(1 个)

Jemima Pulipati
Jemima Pulipati 2020-12-18
Hello,
From my understanding, you are trying to use a symbolic variable in an 'if' condition. But the if condition checks for a definite value and here since there is a symbolic variable, it throws an error.
Here are few observations from the code:
  1. The function handles have to be defined with the variable that is present in the expression
  2. While passing a function handle to subs(), you need not place it in quotes as this is a variable
  3. You may have to use double() to actually substitute the numeric values while referencing f0, f0_prime.
Here is the modified code
clear; clc;
sym h;
f = @(h) 10*pi*h^2-((pi*h^3)/3)-1000;
F = @(h) 20*pi*h-pi*h^2; %calculated by hand
n = 6;
eps = 1*10^-(n+1); %epsilon value
h0 = 6;
for i = 1:20
f0 = vpa(subs(f,'h','h0'));
f0_prime = vpa(subs(F,'h','h0'));
Y = (h0-double(subs(f0)))/double(subs(f0_prime)); % The Formula
error = abs(Y-h0);
if error < eps %checking the error value after each iteration <===== LINE 26
break
end
h0 = Y;
end
Y = Y - rem(Y,10^-n)
Here are some answers from the community which might be of relevance to you.

类别

Help CenterFile Exchange 中查找有关 Elementary Math 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by