Filling results from for loop into an array/matrix?
113 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Emanuele Joy
el 8 de Jun. de 2018
Comentada: Emanuele Joy
el 8 de Jun. de 2018
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?
0 comentarios
Respuesta aceptada
Aquatris
el 8 de Jun. de 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)"
Más respuestas (0)
Ver también
Categorías
Más información sobre Optics en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!