Matrix Dimensions Must Agree Error When Adding Polynomials

3 views (last 30 days)
I have to write a function which adds/subtracts two polynomial coefficient vectors, called
poly_add(p1,p2,operation)
p1 is the first vector
p2 is the second vector
operation is the mode: either 'add' or 'subtract'
The coefficient vectors can be different in size so I have to add zeros accordingly to make them the same length.
This is my code
function p = poly_add( p1, p2, operation )
if length(p1) > length(p2)
num_zeros = length(p1) - length(p2);
p2 = [zeros(1,num_zeros),p2];
elseif length(p2) > length(p1)
num_zeros = length(p2) - length(p1);
p1 = [zeros(1,num_zeros),p1];
end
if operation == 'add'
p = p1 + p2;
elseif operation == 'subtract'
p = p1 - p2;
end
end
Addition works fine but when I try to subtract I get this error:
??? Error using ==> eq
Matrix dimensions must agree.
Error in ==> poly_add at 4
if operation == 'add'
I don't see why this happens. When I just try to do it step by step in command window, it works fine.

Answers (1)

Pulkit Goel
Pulkit Goel on 8 Jul 2020
This is happening because while comparing 'subtract' to 'add', MATLAB is looking for same length of vectors to compare. While adding, since your operation is 'add' which is of same length, there was no error thrown.
You can try using isequal to compare
if isequal(operation,'add')
%your logic
elseif isequal(operation,'subtract')
%yourlogic
end
Or else you may change 'subtract' to 'sub' which may again error out if operation input is not the same size.

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!