Matrix dimension does not agree when using .*

8 ビュー (過去 30 日間)
Sena Ece  Uzungil
Sena Ece Uzungil 2019 年 4 月 1 日
回答済み: Kelly Kearney 2019 年 4 月 1 日
Our code is calculating Taylor polynomials. We are sure that the problem is about P1 because program is plotting PO and f(x). We would really appreciate if anyone can solve our problem.
clc
clear all
close all
h = 0.01; % step size
X = -pi/8:h:7*pi/8; % domain
f=@(X) cot(X); % range
a=5*pi/8
Z1=@(X) diff(cot(X)) %first derivative
Z2=@(X) diff(cot(X),2) ; %second derivative
Z3=@(X) diff(cot(X),3) ; %third derivative
P0=@(X) f(a)*ones(size(X))
P1=@(X) f(a) + Z1(a).*(X-a);
P2=@(X) P1 + Z2(a) ./ factorial(2).*((X-a).^2);
P3=@(X) P2 + Z3(a) ./ factorial(3).*((X-a).^3);
xlim([0.1 3])
ylim([-2.5 2.5])
hold on
plot(X,f(X),'k','Linewidth',2)
plot(X,P0(X),'r','Linewidth',2)
plot(X,P1(X),'g-.','Linewidth',2)
plot(X,P2(X),'b--','Linewidth',2)
plot(X,P3(X),'m:','Linewidth',2)
The error we received:
Error using .*
Matrix dimensions must agree.
Error in Untitled>@(X)f(a)+Z1(a).*(X-a)
Error in Untitled (line 26)
plot(X,P1(X),'g-.','Linewidth',2)

採用された回答

Kelly Kearney
Kelly Kearney 2019 年 4 月 1 日
When you calculate
Y = diff(X,n)
where X is a vector, Y will have length length(X)-n. So you need to adjust X accordingly when plotting, e.g.
plot(X,f(X),'k','Linewidth',2)
plot(X,P0(X),'r','Linewidth',2)
plot(X(1:end-1),P1(X),'g-.','Linewidth',2)
plot(X(1:end-2),P2(X),'b--','Linewidth',2)
plot(X(1:end-3),P3(X),'m:','Linewidth',2)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by