User-Defined function to add polynomials

function p= polyno(p1,p2,operation)
%Write a user-defined function that adds are substract polynomials of any two orders
len_p1=length(p1);
len_p2=length(p2);
if len_p1 > len_p2
tmp=[zeros(1:len_p1-len_p2),p2];
p2=tmp;
elseif len_p1 < len_p2
tmp=[zeros(1:len_p2-len_p1),p1];
p1=tmp;
end
if operation == 'Add'
p = p1 + p1;
elseif operation == 'Subtract'
p = p1 - p2;
else
error('Must enter "Add" or "Subtract" to complete operation')
end
end
I know there is a lot of problems witht the code, but the main problems is that it wont add diffrent ordered polynomials correctly, and also it doesnt let me subtract polynomials, it tells me theres an error with the line of the code that tells it to add. How would I go about fixing this?

5 件のコメント

Walter Roberson
Walter Roberson 2019 年 12 月 14 日
You should use strcmp not ==
Walter Roberson
Walter Roberson 2019 年 12 月 14 日
Hint: zeros can be called with a difference between lengths. If the difference is positive then zeroes will be creating an appropriate padding. If the difference in length is 0 or negative then zeros will not give an error message and will silently create empty padding. If you think about this you will see that you do not need to tests the relative length first: you can just go ahead and pad and everything will turn out the right size.
Jose De La Pena
Jose De La Pena 2019 年 12 月 14 日
I'm not too entirely sure what "padding" means.
Jose De La Pena
Jose De La Pena 2019 年 12 月 14 日
Additionally, I thought I already encounted for the zeroes with adding extra ones for the difference between the length of the two polynomials.
Walter Roberson
Walter Roberson 2019 年 12 月 14 日
Remember that zeros(1:5) is the same as zeros([1,2,3,4,5]) which creates a n array that is 1 * 2 * 3 * 4 * 5

サインインしてコメントする。

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangePolynomials についてさらに検索

質問済み:

2019 年 12 月 14 日

コメント済み:

2019 年 12 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by