Filling results from for loop into an array/matrix?

118 views (last 30 days)
I have this function that computes the coefficients of a polynomial of a certain degree:
n = input('Degree of polynomial: ');
for k = 1:n
syms x y
z(k) = (x+y)^k;
coeff = coeffs(z(k));
c = double(coeff);
end
And I'm trying to store all the coefficients into one matrix. i.e.
c =
1 1
1 2 1
1 3 3 1
...
Instead my value for "c" is just the last iteration of the loop (c = 1 3 3 1). I tried to change c(k) but it doesn't work. What should I do here?

Accepted Answer

Aquatris
Aquatris on 8 Jun 2018
First thing you should notice is you are assigning c in each iteration not its indices. In other words you are overwriting it. That is the reason why you only get the last iteration value. You need to assign the values to proper locations in the c.
Unfortunatly you cannot have a matrix with different number of columns in each row. You can use cell arrays but they are hard to work with for certain applications. Instead you can first initialize your c matrix as zeros, then assign the values to proper locations as follows;
n = input('Degree of polynomial: ');
c = zeros(n,n+1); %n rows n+1 columns of zeros
for k = 1:n
syms x y
z(k) = (x+y)^k;
coeff = coeffs(z(k));
c(k,1:k+1) = double(coeff); % proper rows and columns to assign the coefficients.
end
c =
1 1 0 0 0 0 0
1 2 1 0 0 0 0
1 3 3 1 0 0 0
1 4 6 4 1 0 0
1 5 10 10 5 1 0
1 6 15 20 15 6 1
The downside is you will have zeros in your matrix. So whenever you wanna get the nth order coefficient you need to call "c(n,1:n+1)"
  1 Comment
Emanuele Joy
Emanuele Joy on 8 Jun 2018
I see. Another thing I tried to do was to initialize a ones matrix and fill that, but I just ended up getting a matrix of:
c =
1 1 1
2 2 2
3 3 3
This clears things up a lot. Thanks for your help!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!