2

I am trying to create a function in MATLAB which will expand a bracket to the power of n, where n is a natural number. This is what I have so far:

function expandb = expandb(x,y,n)
z = my_bincoeff1(n);;
syms v x y
v=1:n+1
for i=1:n+1
    v(i)=z(i)*x.^(n-i+1)*y.^(i-1);
end
a=0
for i=1+n+1
    a=a+v(i)
end

expandb = a;

I get this error when I run it:

??? The following error occurred converting from sym to double:
Error using ==> mupadmex
Error in MuPAD command: DOUBLE cannot convert the input expression into a double
array.
If the input expression contains a symbolic variable, use the VPA function instead.

Error in ==> expandb at 6
    v(i)=z(i)*x.^(n-i+1)*y.^(i-1);

So how do I store 2 variables in an array?

Jacob
  • 34,255
  • 14
  • 110
  • 165
Mobix
  • 21
  • 2
  • Should `expandb` be a function of symbolic variables or a number? – Jacob Dec 12 '10 at 01:27
  • It should be a function of 2 variables. Let's say i have to expand (2x+3y)^4 I would write expandb(2x,3y,4) and the answers would be of the form (2x)^4+... – Mobix Dec 12 '10 at 02:17
  • Is there a reason you don't want to use the function [EXPAND](http://www.mathworks.com/help/toolbox/symbolic/expand.html), i.e. expand((2*x+3*y)^4);? – gnovice Dec 12 '10 at 03:04

1 Answers1

1

The problem is the fact that, even though you first define v as a symbolic object using SYMS, you redefine it to be an array of double values on the next line. Then, in the first iteration of your loop you index the first element of v and try to place a symbolic expression in that element. The error arises when MATLAB tries to convert the symbolic expression to type double to match the type of the other elements of the array v (which it can't do because there are unspecified symbolic objects like x and y in the expression).

The solution below should accomplish what you want:

function v = expandb(x,y,n)
  z = my_bincoeff1(n);
  syms v x y
  v = z(1)*x.^n;  %# Initialize v
  for i = 2:n+1
    v = v+z(i)*x.^(n-i+1)*y.^(i-1);  %# Add terms to v
  end
end
gnovice
  • 125,304
  • 15
  • 256
  • 359