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

조회 수: 110 (최근 30일)
Klaus Gani
Klaus Gani 2020년 12월 15일
답변: Jemima Pulipati 2020년 12월 18일
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에서 Numbers and Precision에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by