Matrix dimension does not agree when using .*

조회 수: 1 (최근 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 CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by