Reputation: 614
I have a problem with creating a polynomial function of arbitrary length in Matlab, that would work, when used with a vector as an argument.
I have to do an algorithm, that includes and returns a value of a polynomial. Bellow is my code:
n = 4 % For simplicity, could be arbitrary positive integer
f = @(x) x.^[0:n] %Coefficients are 1 (for this example), if not, would be multiplied with vector of them
p = @(x) sum(f(x)) %My polynomial
>> p(5)
ans =
781
This goes as planed. But because I need a plot, I need my polynomial to be able to receive vectors of values and return them. But when I do this, an error pops up. Example:
>>p([1 2 3 4])
Error using .^
Matrix dimensions must agree.
Error in @(x)x.^[0:n]
Error in @(x)sum(f(x))
What I want it to return is a vector of length 4 with values of my polynomial [p(1) p(2) p(3) p(4)]
I got around this by creating a values vector with a for loop, but am just wondering, is it possible to change my code, so this would work?
Upvotes: 2
Views: 81
Reputation: 11072
The problem can be easily fixed using a row and a column vector, instead of two row vectors:
p([1 2 3 4]')
and explicitly defining the dimension along which you want to take the summation:
p = @(x) sum(f(x), 2)
Explanation
Note that .^
is an element wise operation. p([1 2 3 4 5])
works, because both row vectors have the same size, but doesn't return the desired result, i.e. it calculates 1^0 + 2^1 + 3^2 + 4^3 + 5^4 = 701
.
Matlab automatically expands (in pseudo matlab code)
[1 .^ [0 1 2 3 4]
2
3
4]
to
[1 1 1 1 .^ [0 1 2 3 4
2 2 2 2 0 1 2 3 4
3 3 3 3 0 1 2 3 4
4 4 4 4] 0 1 2 3 4]
Backward compatibility (2006-2016a)
The definition of f
should be changed because matlab does not support automatic arithmetic expansion yet.
f = @(x) bsxfun(@power, x, 0:n);
Backward compatibility (1996-2005)
bsxfun
didn't exist yet, so one should resort to repmat
.
Upvotes: 2